1.Java创建Excel的表头
public static void createSheet(Workbook workbook, String sheetName, String[] columnTitles) {
Sheet sheet = workbook.createSheet(sheetName);
Row headerRow = sheet.createRow(0);
// 设置表头样式
CellStyle headerStyle = workbook.createCellStyle();
Font headerFont = workbook.createFont();
//设置字体大小
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short) 14);
headerStyle.setFont(headerFont);
// 设置表头边框样式
headerStyle.setBorderTop(BorderStyle.THIN);
headerStyle.setBorderBottom(BorderStyle.THIN);
headerStyle.setBorderLeft(BorderStyle.THIN);
headerStyle.setBorderRight(BorderStyle.THIN);
// 设置自动换行
headerStyle.setWrapText(true);
// 设置对齐方式
headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 设置背景颜色
headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 创建表头
for (int i = 0; i < columnTitles.length; i++) {
sheet.autoSizeColumn(i);
Cell cell = headerRow.createCell(i);
cell.setCellValue(columnTitles[i]);
cell.setCellStyle(headerStyle);
}
sheet.getRow(0).setHeightInPoints(70);
}
2.Java将数据写入到Excel中
public <T> void processGatherData(Workbook workbook, List<T> gatherList, String sheetName, String[] columnTitles) throws IllegalAccessException, NoSuchFieldException {
ExcelUtil.createSheet(workbook, sheetName, columnTitles);
Sheet sheet = workbook.getSheetAt(0);
if (gatherList != null && !gatherList.isEmpty()) {
for (int rowIndex = 0; rowIndex < gatherList.size(); rowIndex++) {
Row dataRow = sheet.createRow(rowIndex + 1);
T gatherData = gatherList.get(rowIndex);
int count = 0;
Field[] fields = gatherData.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
Cell cell = dataRow.createCell(count++);
Object fieldValue = field.get(gatherData);
ExcelUtil.setCellValue(cell, fieldValue);
} catch (IllegalAccessException e) {
log.error("处理数据出错:" + e.getClass().getSimpleName() + " - " + e.getMessage());
}
}
}
}
}