Apache POI提供了Java程序读取和写入MS Office文档的接口。 对于Excel文档读写: -HSSF:提供读写MS Excel的xls文件的功能。 -XSSF:提供读写MS Excel的xlsx文件的功能。
Java使用POI实现对Excel文件的读写操作
本篇的ExcelUtils工具类,主要针对于**一行数据(row)作为一个实例(t)**的情况使用。
Excel对象
Java对象
表格(sheet)
List<T>
行(row)
T 的一个实例 (t)
单元格(cell)
对象 t 的某个属性
1package com.liziczh.ims.tools; 2 3import org.apache.poi.hssf.usermodel.HSSFCellStyle; 4import org.apache.poi.ss.usermodel.*; 5import org.apache.poi.xssf.usermodel.XSSFWorkbook; 6 7import java.io.File; 8import java.io.FileInputStream; 9import java.io.FileOutputStream; 10import java.io.IOException; 11import java.lang.reflect.Field; 12import java.util.LinkedList; 13import java.util.List; 14 15/** 16 * Excel文件读写工具类:针对一行数据(row)作为一个实例(t)的情况 17 */ 18public class ExcelUtils { 19 /** 20 * 针对xlsx文件,使用XSSFWorkbook,要求excel版本在2007以上 21 * 22 * @param T 泛型类,行对象 23 * @param filepath 文件路径 24 * @return 25 * @throws Exception 26 */ 27 public static <T> List<T> readExcel(Class T,String filepath){ 28 try { 29 if(filepath != null && !"".equals(filepath)){ 30 // 工作簿 31 Workbook xwb = new XSSFWorkbook(new FileInputStream(filepath)); 32 // 表格 33 Sheet sheet = null; 34 // 行 35 Row row = null; 36 // 单元格 37 Cell cell = null; 38 // 表 39 sheet = xwb.getSheetAt(0); 40 List<T> sheetList = new LinkedList<>(); 41 for(int i = sheet.getFirstRowNum()+1; i < sheet.getPhysicalNumberOfRows(); i++){ 42 // 获取第i行 43 row = sheet.getRow(i); 44 // 利用反射生成一个实例 45 T t = (T) T.newInstance(); 46 // 依此获取单元格放入对象t中 47 for(int j = row.getFirstCellNum(); j < row.getPhysicalNumberOfCells(); j++){ 48 // 获取第i行第j列的单元格, 49 cell = row.getCell(j); 50 // 获取对象的属性数组 51 Field[] fs = t.getClass().getDeclaredFields(); 52 // 设置属性为可访问 53 fs[j].setAccessible(true); 54 // 类型转换:将单元格内容先转为String再转为当前属性所对应的类型 55 if(fs[j].getType() == String.class){ 56 fs[j].set(t,fs[j].getType().cast(cell.toString())); 57 } else if (fs[j].getType() == int.class) { 58 fs[j].set(t,new Integer(cell.toString())); 59 } else if(fs[j].getType() == short.class){ 60 fs[j].set(t,new Short(cell.toString())); 61 }else if(fs[j].getType() == long.class){ 62 fs[j].set(t,new Long(cell.toString())); 63 }else if(fs[j].getType() == byte.class){ 64 fs[j].set(t,new Byte(cell.toString())); 65 }else if(fs[j].getType() == float.class){ 66 fs[j].set(t,new Float(cell.toString())); 67 }else if(fs[j].getType() == double.class){ 68 fs[j].set(t,new Double(cell.toString())); 69 } 70 } 71 // 将对象t添加到集合中 72 sheetList.add(t); 73 } 74 return sheetList; 75 } 76 } catch (Exception e) { 77 e.printStackTrace(); 78 } 79 return null; 80 } 81 82 /** 83 * 针对xlsx文件,使用XSSFWorkbook,要求excel版本在2007以上 84 * 85 * @param list 数据 86 * @param T 泛型类,行对象 87 * @param colNames 表头信息, 88 * @param filepath 文件路径 89 * @return 90 * @throws Exception 91 */ 92 public static <T> void writeExcel(List<T> list,Class T,String[] colNames,String filepath) { 93 if(filepath != null && !"".equals(filepath)){ 94 // 工作簿 95 Workbook workbook = new XSSFWorkbook(); 96 // 表格 97 Sheet sheet = workbook.createSheet("0"); 98 // 行 99 Row row = null; 100 // 单元格 101 Cell cell = null; 102 // 设置表头样式 103 CellStyle headerStyle = workbook.createCellStyle(); 104 headerStyle.setAlignment(HorizontalAlignment.CENTER); 105 Font headerFont = workbook.createFont(); 106 headerFont.setBold(true); 107 headerStyle.setFont(headerFont); 108 // 通过colNames数组生成表头 109 row = sheet.createRow(0); 110 for (int c = 0; c < colNames.length; c++) { 111 cell = row.createCell(c); 112 cell.setCellValue(colNames[c]); 113 cell.setCellStyle(headerStyle); 114 } 115 // 设置单元格样式 116 CellStyle cellStyle = workbook.createCellStyle(); 117 cellStyle.setAlignment(HorizontalAlignment.CENTER); 118 // 通过一个List生成表内数据 119 for (int r = 0; r < list.size(); r++) { 120 // 获取一个List元素(即一个T的实例) 121 T t = list.get(r); 122 // 获取对象t的所有属性 123 Field[] fs = t.getClass().getDeclaredFields(); 124 // 生成行 125 row = sheet.createRow(r + 1); 126 // 依此获取对象t的属性值 赋予 单元格 127 for (int j = 0; j < fs.length; j++) { 128 try { 129 // 设置属性为可访问 130 fs[j].setAccessible(true); 131 // 生成一个单元格 132 cell = row.createCell(j); 133 // 将属性值赋予单元格 134 cell.setCellValue(String.valueOf(fs[j].get(t))); 135 cell.setCellStyle(cellStyle); 136 } catch (IllegalAccessException e) { 137 e.printStackTrace(); 138 } 139 } 140 } 141 // 设置表名 142 workbook.setSheetName(0, T.getName()); 143 // 生成xlsx文件 144 FileOutputStream out = null; 145 try { 146 out = new FileOutputStream(new File(filepath)); 147 workbook.write(out); 148 } catch (IOException e) { 149 e.printStackTrace(); 150 }finally { 151 try { 152 out.close(); 153 } catch (IOException e) { 154 e.printStackTrace(); 155 } 156 } 157 } 158 } 159 160 161}