java导出excel多级表头
时间: 2023-06-05 13:47:36 浏览: 810
Java导出Excel多级表头可以使用Apache POI库,递归创建表头行,设置单元格样式和合并单元格,实现复杂的多级表头。
首先,创建一个方法用于递归创建表头,并返回表头行的最终行数。方法参数为表头数据、Excel Sheet对象、起始行、最后一列、当前级别。在方法内部,根据当前级别创建表头行并设置样式,根据下一级别的数据递归创建子表头行,最后合并单元格并返回创建的最终行数。
其次,调用上述方法创建所有表头行后,根据数据填充Excel表格并设置单元格样式。最后将数据写入Excel文件并保存即可。
示例代码:
private static int createHeader(List<List<String>> headerData, Sheet sheet, int startRow, int lastCol, int level) {
int endRow = startRow;
Row row = sheet.createRow(startRow);
row.setHeightInPoints(25f);
CellStyle style = sheet.getWorkbook().createCellStyle();
Font font = sheet.getWorkbook().createFont();
font.setBold(true);
style.setFont(font);
for (int i = 0; i < headerData.size(); i++) {
Cell cell = row.createCell(i);
cell.setCellValue(headerData.get(i).get(0));
cell.setCellStyle(style);
if (headerData.get(i).size() > 1) {
int rowspan = createHeader(headerData.get(i).subList(1, headerData.get(i).size()), sheet, startRow + 1, lastCol, level + 1);
sheet.addMergedRegion(new CellRangeAddress(startRow, startRow + rowspan - 1, i, i));
} else {
endRow = Math.max(endRow, startRow);
}
}
if (level == 0) {
for (int i = headerData.size(); i <= lastCol; i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(style);
}
}
return endRow - startRow + 1;
}
public static void writeExcel(List<List<String>> headerData, List<List<Object>> data, String filePath) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
int lastCol = headerData.get(0).size() - 1;
int lastRow = createHeader(headerData, sheet, 0, lastCol, 0);
CellStyle style = sheet.getWorkbook().createCellStyle();
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
for (int i = 0; i < data.size(); i++) {
Row row = sheet.createRow(lastRow + i);
List<Object> rowData = data.get(i);
for (int j = 0; j <= lastCol; j++) {
Cell cell = row.createCell(j);
cell.setCellValue(rowData.get(j).toString());
cell.setCellStyle(style);
}
}
FileOutputStream outputStream = new FileOutputStream(filePath);
workbook.write(outputStream);
outputStream.close();
}
阅读全文