环境准备
JDK1.8+
maven
实现范围
将集合数据+表头 转换成具体的Excel对象,注意这个范围。将Excel对象转换为文件是另外一个方法的事
三方包引入
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
API方法
/**
* @param sheetName excel 专业概念
* @param tableNames 表头名称集合
* @param attributeName 表头对应到属性的名称
* @param objs 具体数据的集合
* @return HSSFWorkbook POI Excel 表格数据载体
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public HSSFWorkbook writeToExcel(String sheetName, List<String> tableNames, List<String> attributeName, List objs) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
//POI API类
HSSFWorkbook workbook = new HSSFWorkbook();
//创建excel sheet
workbook.createSheet(sheetName);
//添加表头,表头添加在第一行
Row row = workbook.getSheet(sheetName).createRow(0); //创建第一行
//因为表头一行存在多列,循环存放
for (int i = 0; i < tableNames.size(); i++) {
Cell cell = row.createCell(i);
cell.setCellValue(tableNames.get(i));
}
//循环放置集合数据
for (int i = 0; i < objs.size(); i++) {
int rowCount = workbook.getSheet(sheetName).getLastRowNum() + 1;
Row rowNew = workbook.getSheet(sheetName).createRow(rowCount);
Class<? extends Object> class_ = objs.get(i).getClass();
for (int j = 0; j < attributeName.size(); j++) {
String title = attributeName.get(j);
String UTitle = Character.toUpperCase(title.charAt(0)) + title.substring(1, title.length());
String methodName = "get" + UTitle;
Method method = class_.getDeclaredMethod(methodName);
String data = method.invoke(objs.get(i)).toString();
Cell cell = rowNew.createCell(j);
cell.setCellValue(data);
}
}
return workbook;
}