import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class ReadWriteExcelFile {
private static Properties props = new Properties();
static {
try {
InputStream is = ReadWriteExcelFile.class.getClassLoader().getResourceAsStream("META-INF/ExcelHeader.properties");
props.load(is);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getValue(String key) {
String value = "";
if (props.containsKey(key)) {
value = props.getProperty(key, "");
}
return value;
}
private final static Logger logger = LoggerFactory.getLogger(ReadWriteExcelFile.class);
@SuppressWarnings({ "resource", "rawtypes" })
public static void readXLSFile() throws IOException
{
InputStream ExcelFileToRead = new FileInputStream("E:/source/Test.xls");
HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead); HSSFSheet sheet=wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell; Iterator rows = sheet.rowIterator(); while (rows.hasNext())
{
row=(HSSFRow) rows.next();
Iterator cells = row.cellIterator(); while (cells.hasNext())
{
cell=(HSSFCell) cells.next(); if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
//U Can Handel Boolean, Formula, Errors
}
}
System.out.println();
} }
public static void writeXLSFile(List<? extends Recording> records) throws IOException{
//String directory=getValue("excel.file.directory");
String directory="E:/source";
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(d);
Recording record=records.get(0);
Class<? extends Recording> cls=record.getClass();
String className=cls.getCanonicalName();
String[] nameAlias=className.split("\\.");
String excelFileName=directory+File.separator+nameAlias[nameAlias.length-1]+date+".xls";
writeXLSFile(records,excelFileName);
} @SuppressWarnings("resource")
public static void writeXLSFile(List<? extends Recording> records,String excelFileName) throws IOException{ //String excelFileName = "E:/source/Test.xls";
String sheetName = "Sheet1";//name of sheet HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sheetName) ;
Recording record;
//excel header
HSSFRow row = sheet.createRow(0);
record=records.get(0);
Class<? extends Recording> cls=record.getClass();
String className=cls.getCanonicalName();
String[] nameAlias=className.split("\\.");
Field[] fields=cls.getDeclaredFields();
//去除serialVersionUID列,
List<Field> fieldsNoSer=new ArrayList<Field>();
for(int i=0;i<fields.length;i++){
String fieldName=fields[i].getName();
if(fieldName.equalsIgnoreCase("serialVersionUID")){
continue;
}else{
fieldsNoSer.add(fields[i]);
}
}
for(int i=0;i<fieldsNoSer.size();i++){
HSSFCell cell = row.createCell(i);
String fieldName=fieldsNoSer.get(i).getName();
cell.setCellValue(getValue(nameAlias[nameAlias.length-1]+"."+fieldName));
} //iterating r number of rows
for (int r=0;r < records.size(); r++ )
{
row = sheet.createRow(r+1);
record=records.get(r);
//table content
for (int c=0;c < fieldsNoSer.size(); c++ )
{
HSSFCell cell = row.createCell(c);
//加header,方法总变量的首字母大写
String fieldName=fieldsNoSer.get(c).getName();
try {
Method method=cls.getDeclaredMethod("get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1));
Object ret=method.invoke(record);
if(null!=ret){
cell.setCellValue(method.invoke(record).toString());
} } catch (Exception e) {
logger.info("write xls error,please check it");
}
}
}
FileOutputStream fileOut = new FileOutputStream(excelFileName); //write this workbook to an Outputstream.
wb.write(fileOut);
fileOut.flush();
fileOut.close();
} @SuppressWarnings({ "resource", "unused", "rawtypes" })
public static void readXLSXFile() throws IOException
{
InputStream ExcelFileToRead = new FileInputStream("E:/source/Test1.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead); XSSFWorkbook test = new XSSFWorkbook(); XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell; Iterator rows = sheet.rowIterator(); while (rows.hasNext())
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(XSSFCell) cells.next(); if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
//U Can Handel Boolean, Formula, Errors
}
}
System.out.println();
} } @SuppressWarnings("resource")
public static void writeXLSXFile() throws IOException { String excelFileName = "E:/source/Test1.xlsx";//name of excel file String sheetName = "Sheet1";//name of sheet XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(sheetName) ; //iterating r number of rows
for (int r=0;r < 5; r++ )
{
XSSFRow row = sheet.createRow(r); //iterating c number of columns
for (int c=0;c < 5; c++ )
{
XSSFCell cell = row.createCell(c); cell.setCellValue("Cell "+r+" "+c);
}
} FileOutputStream fileOut = new FileOutputStream(excelFileName); //write this workbook to an Outputstream.
wb.write(fileOut);
fileOut.flush();
fileOut.close();
} public static void main(String[] args) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
List<Log> logs=new ArrayList<Log>();
for(int i=1;i<2;i++){
Log log=new Log();
log.setId(Long.parseLong(""+(i+6)));
log.setUserId(Long.parseLong(""+i));
log.setUserName("www"+i);
logs.add(log);
}
writeXLSFile(logs,"E:/source/aa.xls"); }

java poi操作excel示例代码的更多相关文章

  1. java POI创建Excel示例(xslx和xsl区别 )

    Java用来处理office类库有很多,其中POI就是比较出名的一个,它是apache的类库,现在版本到了3.10,也就是2014年2月8号这个版本. 在处理PPT,Excel和Word前,需要导入以 ...

  2. java poi操作excel 添加 锁定单元格保护

    Excel的book保护是很常用的,主要是不想让别人修改Excel的时候用.这样能够避免恶意随便修改数据,提高数据的可信度. 下面介绍JAVA POI来实现设置book保护: 使用HSSFSheet类 ...

  3. Java POI 操作Excel(读取/写入)

    pom.xml依赖: <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi< ...

  4. java poi 操作

    Java POI 操作Excel(读取/写入) https://www.cnblogs.com/dzpykj/p/8417738.html Java操作Excel之Poi基本操作 https://my ...

  5. 在java poi导入Excel通用工具类示例详解

    转: 在java poi导入Excel通用工具类示例详解 更新时间:2017年09月10日 14:21:36   作者:daochuwenziyao   我要评论   这篇文章主要给大家介绍了关于在j ...

  6. java使用POI操作excel文件,实现批量导出,和导入

    一.POI的定义 JAVA中操作Excel的有两种比较主流的工具包: JXL 和 POI .jxl 只能操作Excel 95, 97, 2000也即以.xls为后缀的excel.而poi可以操作Exc ...

  7. JAVA的POI操作Excel

    1.1Excel简介 一个excel文件就是一个工作簿workbook,一个工作簿中可以创建多张工作表sheet,而一个工作表中包含多个单元格Cell,这些单元格都是由列(Column)行(Row)组 ...

  8. java 使用jxl poi 操作excel

    java操作excel  创建.修改 xls 文件 JAVA操作Excel文件 Java生成和操作Excel文件 java导出Excel通用方法 Java 实现导出excel表 POI Java PO ...

  9. java里poi操作excel的工具类(兼容各版本)

    转: java里poi操作excel的工具类(兼容各版本) 下面是文件内具体内容,文件下载: import java.io.FileNotFoundException; import java.io. ...

随机推荐

  1. 外部样式表声明的样式并不会进入style对象

    在网页设计当中,我们注重网页的行为(js).结构(HTLM).样式(css)分离开 内联样式表或者内部样式表声明的样式信息都会进入style对象. 我们可以测试一下: 但是我们的外部样式表,也就是通过 ...

  2. html页面颜色名称和颜色值转换

    public static string ToHtmlColor(string colorName) { try { if (colorName.StartsWith("#")) ...

  3. dedecms4张关键表解析之2

    4张核心表的具体情况: 1.第一张表:dede_arctype  栏目表 字段解析: topid:上一级的id(0表示为顶级,1表示为下一级....) typename: 栏目名称 typedir:栏 ...

  4. Scala和范畴论 -- 对Monad的一点认识

    Scala和范畴论 -- 对Monad的一点认识 背景 所有一切的开始都是因为这句话:一个单子(Monad)说白了不过就是自函子范畴上的一个幺半群而已,有什么难以理解的.第一次看到这句话是在这篇文章: ...

  5. appium使用教程(二)-------------连接手机

    1. 安装驱动 说明:如果驱动装不上,可以使用第三方的工具去安装.(一般来说还是用第三方) 大概就是这个样子索. 2. 开启usb调试 1)开发者选项打开(不知道怎么打开的问度娘) 2)开启USB调试 ...

  6. Spring Cloud学习笔记【八】服务网关 Zuul(过滤器)

    在上篇文章中我们了解了 Spring Cloud Zuul 作为网关所具备的最基本功能:路由(Router),下面我们将关注 Spring Cloud Zuul 的另一核心功能:过滤器(Filter) ...

  7. 洛谷 P1604 B进制星球

    P1604 B进制星球 题目背景 进制题目,而且还是个计算器~~ 题目描述 话说有一天,小Z乘坐宇宙飞船,飞到一个美丽的星球.因为历史的原因,科技在这个美丽的星球上并不很发达,星球上人们普遍采用B(2 ...

  8. MYSQL 更新时间自己主动同步与创建时间默认值共存问题

    本文作者:苏生米沿 本文地址:http://blog.csdn.net/sushengmiyan/article/details/50326259 在使用SQL的时候,希望在更新数据的时候自己主动填充 ...

  9. 125.C++输入小结

    #include <iostream> #include <iomanip> #include <cstring> #include <cstdlib> ...

  10. hashCode 和 equals 方法

    hashCode 和 equals 方法 hashCode()和equals()定义在Object类中,这个类是所有java类的基类,所以所有的java类都继承这两个方法. 使用hashCode()和 ...