Java工具类------实体类列表写入excel
java
/**
* 将实体类 List 数据写入 Excel 文件
* @param dataList 实体类对象列表
* @param filePath Excel 文件路径
* @param sheetName Sheet 名称
* @param <T> 泛型类型
* @throws IOException 文件操作异常
* @throws IllegalAccessException 反射异常
*/
public static <T> void writeListToExcel(List<T> dataList, String filePath, String sheetName)
throws IOException, IllegalAccessException {
// 如果数据列表为空,直接返回
if (dataList == null || dataList.isEmpty()) {
return;
}
Workbook workbook;
File file = new File(filePath);
// 判断文件是否存在
if (file.exists()) {
// 文件存在,加载现有工作簿
try (FileInputStream inputStream = new FileInputStream(file)) {
workbook = new XSSFWorkbook(inputStream);
}
} else {
// 文件不存在,创建新工作簿
workbook = new XSSFWorkbook();
}
// 检查Sheet是否存在
Sheet sheet = workbook.getSheet(sheetName);
if (sheet != null) {
// Sheet存在,先删除再创建(相当于清空)
int sheetIndex = workbook.getSheetIndex(sheet);
workbook.removeSheetAt(sheetIndex);
sheet = workbook.createSheet(sheetName);
} else {
// Sheet不存在,直接创建
sheet = workbook.createSheet(sheetName);
}
// 获取第一个对象的类信息
Class<?> clazz = dataList.get(0).getClass();
Field[] fields = clazz.getDeclaredFields();
// 创建标题行
Row headerRow = sheet.createRow(0);
CellStyle headerStyle = createHeaderStyle(workbook);
// 写入标题(属性名)
for (int i = 0; i < fields.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(fields[i].getName());
cell.setCellStyle(headerStyle);
}
// 写入数据行
for (int i = 0; i < dataList.size(); i++) {
Row row = sheet.createRow(i + 1);
T item = dataList.get(i);
for (int j = 0; j < fields.length; j++) {
fields[j].setAccessible(true); // 允许访问私有字段
Object value = fields[j].get(item);
Cell cell = row.createCell(j);
if (value != null) {
if (value instanceof Number) {
cell.setCellValue(((Number) value).doubleValue());
} else if (value instanceof Boolean) {
cell.setCellValue((Boolean) value);
} else {
cell.setCellValue(value.toString());
}
}
}
}
// 自动调整列宽
for (int i = 0; i < fields.length; i++) {
sheet.autoSizeColumn(i);
}
// 写入文件
try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
workbook.write(outputStream);
} finally {
workbook.close();
}
}
/**
* 创建标题行样式
* @param workbook 工作簿
* @return 单元格样式
*/
private static CellStyle createHeaderStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBold(true);
style.setFont(font);
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
return style;
}