如何生成可变表头的excel

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

1、实现功能:

传入一个表头和数据,将数据导入到Excel中。

为了便于项目的扩展,数据传入通过泛型集合传入,获取数据时,通过反射的方式获取,这样无论你的表头是多少项,我都能很方便的生成。另外为了便于数据的管理,我每天都会自动生成一个文件夹,excel生成在相应的文件夹中。文件的根目录通过读取项目中的PRoperties文件获取(详情可查看:http://www.cnblogs.com/0201zcr/p/4700418.html)。好啦,接下来直接进入代码开发吧。

2、所需jar包

这里使用的是通过poi的方式将数据导入到excel中。

3、代码设计

1)、properties文件内容

filePath=E\:/appData

2)、获取文件保存的根目录(来自项目中的properties文件)

importjava.io.BufferedInputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStream;importjava.util.Properties;publicclassGetFilePlace

{/*** 读取文件,获取excel保存的根目录

*@returnexcel保存的根目录*/publicString getFilePath()

{

String dir= System.getProperty("user.dir");//获得tomcat所在的工作路径//获取到存储了文件存储位置的filedir.properties 文件路径String realDir = dir + File.separator + "src" + File.separator +"META-INF" + File.separator + "filedir.properties";/*String realDir = dir.substring(0, dir.length()-4) + File.separator +"webapps" + File.separator + "generateExcels"

+ File.separator + "classes" + File.separator + "META-INF" + File.separator + "config" + File.separator + "filedir.properties";*/returnrealDir;

}/*** 获取filePath路径【properities文件】中key对应的值,

*@paramfilePath properities文件路径【包含properities文件】

*@paramkey 要查找的key值

*@returnkey对应的value*/publicString GetValueByKey(String filePath, String key)

{

Properties pps=newProperties();try{

InputStream in=newBufferedInputStream (newFileInputStream(filePath));

pps.load(in);

String value=pps.getProperty(key);

in.close();returnvalue;

}catch(IOException e) {

e.printStackTrace();returnnull;

}

}/*** 查询properities文件中可以对应的存储地点

*@paramkey 查询主键

*@returnkey对应的存储地址*/publicString getFileDirFromProperties(String key)

{returnGetValueByKey(getFilePath(),key);

}publicstaticvoidmain(String[] args)

{

System.out.println(newGetFilePlace().getFileDirFromProperties("filePath"));

}

}

3)、生成文件夹

importjava.io.File;importjava.text.SimpleDateFormat;importjava.util.Calendar;publicclassGenerateFold

{/*** 查询当前生成的excel需要存在在哪个路径,如果存在则存储在相应的位置,否则生成改目录, 每天生成一个文件夹,文件夹的命名规则为 年月日的时间戳

*@paramfoldName 生成excel保存路径

*@return现在的excel需要保存路径*/publicString getFold(String foldName)

{

SimpleDateFormat format=newSimpleDateFormat("yyyyMMdd");

String todayStr=format.format(Calendar.getInstance().getTime());

String foldPath= foldName + File.separator +todayStr;

File file=newFile(foldPath);if(!file.exists() && !file.isDirectory())

{

System.out.println("不存在");

file.mkdirs();

}else{

System.out.println("存在");

}returnfoldPath;

}

}

4)、生成excel

importjava.io.File;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.OutputStream;importjava.lang.reflect.InvocationTargetException;importjava.lang.reflect.Method;importjava.text.SimpleDateFormat;importjava.util.ArrayList;importjava.util.Calendar;importjava.util.List;importjava.util.UUID;importorg.apache.poi.hssf.usermodel.HSSFCell;importorg.apache.poi.hssf.usermodel.HSSFCellStyle;importorg.apache.poi.hssf.usermodel.HSSFRow;importorg.apache.poi.hssf.usermodel.HSSFSheet;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.hssf.util.Region;importorg.apache.poi.ss.usermodel.CellStyle;importcom.zcr.until.GetFilePlace;importcom.zcr.until.User;/*** 生成excel

*@authorzcr

**/publicclassGenerateExcel

{/*** 通过关键字查询properties文件相应文件的存储位置,根据表头顺序将数据保存到相应文件路径的xls文件中, 文件的命名规则是时间戳加一串全球唯一编码

*@paramfileDir //查找文件存储根目录

*@paramhead //表头

*@paramlist //数据

*@return//文件的保存路径及其名字的字符串*/public<T> String generateExcels(String fileDir,String [] head,List<T>list)

{//获得存储的路径//String savePath = new GetFilePlace().getFileDirFromProperties(key);//文件存储名字String saveFileName = "";

SimpleDateFormat format=newSimpleDateFormat("yyyyMMddHHmmssSS");

saveFileName+=format.format(Calendar.getInstance().getTime());

UUID uuid= UUID.randomUUID();//全球唯一编码saveFileName+= "-" +uuid.toString();

HSSFWorkbook workbook=newHSSFWorkbook();

HSSFSheet sheet=workbook.createSheet();

workbook.setSheetName(0,"APP数据");//设置表格工作簿名称HSSFCellStyle cellStyle =workbook.createCellStyle();

cellStyle.setAlignment(CellStyle.ALIGN_CENTER);

cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);

HSSFRow titleRow= sheet.createRow(0);

sheet.addMergedRegion(newRegion(0,(short)0,0,(short)(head.length-1)));

HSSFCell titleCell= titleRow.createCell(0);

titleCell.setCellValue("AAP数据____ ");

titleCell.setCellStyle(cellStyle);

HSSFRow row1= sheet.createRow(1);//设置表头for(inti = 0 ; i < head.length ; i++)

{

HSSFCell cell=row1.createCell(i);

cell.setCellValue(head[i]);//设置值cell.setCellStyle(cellStyle);//设置样式}if(null!= list && list.size() > 0)

{intsize =list.size();

Class classType= list.get(0).getClass();for(inti = 0,rowNum=2 ; i < size ; i ++,rowNum++)

{

HSSFRow rows=sheet.createRow(rowNum);

T t=list.get(i);//添加数据行for(intj = 0 ; j < head.length ; j++)

{//获得首字母String firstLetter = head[j].substring(0,1).toUpperCase();//获得get方法,getName,getAge等String getMethodName = "get" + firstLetter + head[j].substring(1);

Method method;try{//通过反射获得相应的get方法,用于获得相应的属性值method = classType.getMethod(getMethodName,newClass[]{});

HSSFCell dataCell=rows.createCell(j);try{

System.out.print(getMethodName+":" + method.invoke(t,newClass[]{}) +",");

dataCell.setCellValue(method.invoke(t,newClass[]{}).toString());

}catch(IllegalArgumentException e)

{

e.printStackTrace();

}catch(IllegalaccessException e)

{

e.printStackTrace();

}catch(InvocationTargetException e)

{

e.printStackTrace();

}//设置值dataCell.setCellStyle(cellStyle);//设置样式}catch(SecurityException e)

{

e.printStackTrace();

}catch(NoSuchMethodException e)

{

e.printStackTrace();

}

}

System.out.println();

}

}else{

System.out.println("没有数据");

}//获得文件存储路径//String fileDir = new GetFilePlace().getFileDirFromProperties(key);saveFileName += ".xls";

String saveFilePathAndName= fileDir + File.separator +saveFileName;

OutputStream out=null;try{

out=newFileOutputStream(saveFilePathAndName);try{

workbook.write(out);//保存文件}catch(IOException e)

{//TODO Auto-generated catch blocke.printStackTrace();

}

}catch(FileNotFoundException e)

{//TODO Auto-generated catch blocke.printStackTrace();

}finally{try{

out.close();

}catch(IOException e)

{//TODO Auto-generated catch blocke.printStackTrace();

}

}returnsaveFilePathAndName;

}/*** 提供外界调用的接口,生成以head为表头,list为数据的excel

*@paramhead //数据表头

*@paramlist //数据

*@return//excel所在的路径*/public<T> String generateExcel(String [] head,List<T>list)

{finalString FilePath = "filePath";

String saveFilePathAndName= "";//获得存储的根目录String savePath =newGetFilePlace().getFileDirFromProperties(FilePath);//获得当天存储的路径String realSavePath =newGenerateFold().getFold(savePath);//生成excel并将存储的路径返回(包含文件名)saveFilePathAndName =generateExcels(realSavePath, head, list);returnsaveFilePathAndName;

}publicstaticvoidmain(String[] args)

{

String [] head= {"name","sex","adress","height","age","jj"};

List<User> list =newArrayList<User>();

User user1=newUser("zhangsan",1,1.1f,"北京","男","AA");

User user2=newUser("lisi",22222,3.2f,"上海","女","BB");

list.add(user1);

list.add(user2);

System.out.println(newGenerateExcel().generateExcel(head,list));//System.out.println(new GenerateExcel().generateExcels("E:\\appData\\20151104",head,list));}

}

5)、测试结果

生成了文件

文件内容如下

properties文件读取可查看:http://www.cnblogs.com/0201zcr/p/4700418.html

读取excel可查看:http://www.cnblogs.com/0201zcr/p/4656779.html

致谢:感谢您的阅读!

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航