列表信息导出为Excel文件,
依赖pom:
XML
Sheet, Row:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</dependency>
XSSFWorkbook
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
实现代码:
override表示是否覆盖现有文件,false,追加;true,覆盖。
java
private <T> void exportExcelToLocal(List<T> list, Class<T> clazz) throws IOException {
if (CollectionUtils.isEmpty(list)) {
return;
}
XSSFWorkbook workbook = null;
File file = new File("src/main/resources/xxx.xlsx");
FileInputStream fis = null;
if (!file.exists()) {
file.createNewFile();
} else {
if (!override) {
fis = new FileInputStream(file);
workbook = new XSSFWorkbook(fis);
}
}
XSSFWorkbook workbookResult = ExcelUtils.exportExcelData(new XSSFWorkbook(), list, clazz, false);
if (Objects.nonNull(workbook)) {
Integer index = workbookResult.getSheetAt(0).getLastRowNum() + 1;
Sheet sheet = workbookResult.getSheetAt(0);
Sheet lastSheet = workbook.getSheetAt(0);
for (int i = 1; i <= lastSheet.getLastRowNum(); ++i) {
Row row = sheet.createRow(index++);
for (int cellIndex = 0; cellIndex < lastSheet.getRow(i).getLastCellNum(); ++cellIndex) {
String value = lastSheet.getRow(i).getCell(cellIndex).getStringCellValue();
row.createCell(cellIndex).setCellValue(value);
}
}
}
FileOutputStream fos = new FileOutputStream(file);
workbookResult.write(fos);
fos.flush();
fos.close();
if (Objects.nonNull(fis)) {
fis.close();
}
}
ExcelUtils:
单次导出操作
java
public static <T> XSSFWorkbook exportExcelData(XSSFWorkbook workbook, List<T> data, Class<T> clazz, boolean template) {
XSSFSheet sheet = workbook.createSheet();
Row rowHeader = sheet.createRow(0);
Map<Integer, Field> fieldMap = analysisAnnotation(clazz);
for(int i = 0; i < fieldMap.size(); ++i) {
Cell cell = rowHeader.createCell(i);
Field field = (Field)fieldMap.get(i + 1);
ExcelBind ea = (ExcelBind)field.getAnnotation(ExcelBind.class);
cell.setCellValue(ea.columnName());
cell.setCellStyle(setRowHeaderStyle(workbook));
cell.setCellType(CellType.STRING);
}
if (!template) {
analysisData(sheet, data, clazz, fieldMap);
}
return workbook;
}
// 数据导出
private static <T> void analysisData(Sheet sheet, List<T> data, Class<T> clazz, Map<Integer, Field> fieldMap) {
for(int i = 0; i < data.size(); ++i) {
Row row = sheet.createRow(i + 1);
T t = data.get(i);
Class<?> aClass = t.getClass();
for(int j = 0; j < fieldMap.size(); ++j) {
Field declaredField = (Field)fieldMap.get(j + 1);
declaredField.setAccessible(true);
String key = declaredField.getName();
Object value = "";
try {
value = declaredField.get(t) == null ? "" : declaredField.get(t);
} catch (IllegalAccessException var13) {
var13.printStackTrace();
}
if ("java.util.Date".equals(declaredField.getType().getName())) {
ExcelBind ea = (ExcelBind)declaredField.getAnnotation(ExcelBind.class);
if (StringUtils.isNotEmpty(ea.dateFormat())) {
value = (new SimpleDateFormat(ea.dateFormat())).format(value);
}
}
row.createCell(j).setCellValue(value.toString());
}
}
}