java poi对于excel的读写与反射的结合使用
本人目前还在学习阶段,部分代码写的不够完善,也有参考网上的代码片段,只是结合自己的想法,希望对poi导入导出做个适合于自己使用的封装,尽量把常用的工具能封装成自己的jar,便于以后工作学习中的使用。
工作学习中难免需要将数据导入导出到excel表中,java 也有许多jar包支持这部分操作,我使用的就是poi包进行excel的导入导出。新建项目就就免了,我用的是mvn构建的,主要的poi依赖:
<!-- poi依赖 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10-FINAL</version>
</dependency>
前期工作准备完成,开始代码部分:
/**
* 通过传入对象list集合写入excel表
* @param contentList 需写入的list集合对象
* @param outpath excel输出路径,包含excel文件名
* @param <T>
* @throws IOException
*/
public static <T> void writeExcel(List<T> contentList , String outpath) throws IOException{
if(contentList !=null && outpath !=null){
//创建工作簿,若包含".xlsx"则认为是10版本,否则用03版
Workbook wb=new HSSFWorkbook();
if(outpath.contains(".xlsx")){
wb=new XSSFWorkbook();
}
CreationHelper helper=wb.getCreationHelper();
//
Sheet sheet=wb.createSheet("sheet1");
//利用反射获取传入对象第一个元素的所有属性
Field[] fields=contentList.get(0).getClass().getDeclaredFields();
Row row;
Cell cell;
//遍历内容list,每行
for (int i=0;i<contentList.size();++i){
//创建第一行
row =sheet.createRow(i);
//设置行高
row.setHeightInPoints(20.0F);
//遍历元素属性,每列
for (int j=0;j<fields.length;j++){
//创建单元格样式
CellStyle cellStyle=createStyleCell(wb);
cell = row.createCell(j);
//设置居中对齐
cellStyle=setCellStyleAlignment(cellStyle);
cellStyle=setCellFormat(helper,cellStyle);
//设置单元格样式
cell.setCellStyle(cellStyle);
//获取当前行内容对象
Object o = co