EasyExcel导出动态表头
实际开发中,出现Excel表头即列数不固定,列的数量动态变化的情况。例如用户答卷的答案数量,各种不固定指标等等。
需要导出这种excel,下面介绍如何使用EasyExcel导出动态的表头。
设置header
需要返回对应的数据结构:
private List<List<String>> getHeader() {
List<List<String>> header = new ArrayList<>();
// 模拟查询,设置表头
header.add(List.of("批次"));
header.add(List.of("行号"));
header.add(List.of("数据"));
header.add(List.of("提交时间"));
return header;
}
查询rows
private List<Map<Integer, String>> getRow(int pageSize, int pageNum) {
List<Map<Integer, String>> rows = new ArrayList<>();
// 模拟查询数据,这里可以追加分页查询
// pageHelper.startPage(pageNum, pageSize);
for (int i = 0; i < 3; i++) {
Map<Integer, String> row = new LinkedHashMap<>();
row.put(0, "批次" + i);
row.put(1, "行号" + i);
row.put(2, "数据" + i);
rows.add(row);
}
return rows;
}
使用writeTable持续分批写入
excelWrite.fill方法可以持续分批写入,但是需要提供模板,这里我们是动态的表头,没有模板。所以使用writeTable分批写入
// 创建WriteTable并指定起始行
WriteTable writeTable = EasyExcel.writerTable(batch)
.needHead(false)
.relativeHeadRowIndex(currentRow - 1)
.build();
// 写入数据
excelWriter.write(batchData, writeSheet, writeTable);
System.out.println("批次" + (batch + 1) + ": 写入" + actualSize + "行,从第" +
currentRow + "行开始,relativeHeadRowIndex=" + (currentRow - 1));
// 更新当前行号
currentRow += actualSize;
完整代码
public void exportWithAppend(HttpServletResponse response) throws IOException {
// 设置响应头...
// 准备表头
List<List<String>> header = new ArrayList<>();
header.add(Arrays.asList("批次"));
header.add(Arrays.asList("行号"));
header.add(Arrays.asList("数据"));
ExcelWriter excelWriter = null;
try {
excelWriter = EasyExcel.write(response.getOutputStream())
.head(header)
.build();
WriteSheet writeSheet = EasyExcel.writerSheet("数据").build();
// 模拟分批查询
int batchSize = 3;
int totalCount = 7;
int totalBatches = (totalCount + batchSize - 1) / batchSize;
// 记录当前写入的行号(表头占1行,所以从2开始)
int currentRow = 2;
for (int batch = 0; batch < totalBatches; batch++) {
// 计算当前批次的实际数据量
int actualSize = Math.min(batchSize, totalCount - batch * batchSize);
// 模拟查询数据,包含批次号和行号信息
List<Map<String, Object>> batchData = new ArrayList<>();
for (int i = 0; i < actualSize; i++) {
Map<String, Object> row = new HashMap<>();
row.put("批次", batch + 1);
row.put("行号", currentRow + i);
row.put("数据", "批次" + (batch + 1) + "-行" + (currentRow + i));
batchData.add(row);
}
// 创建WriteTable并指定起始行
WriteTable writeTable = EasyExcel.writerTable(batch)
.needHead(false)
.relativeHeadRowIndex(currentRow - 1)
.build();
// 写入数据
excelWriter.write(batchData, writeSheet, writeTable);
System.out.println("批次" + (batch + 1) + ": 写入" + actualSize + "行,从第" +
currentRow + "行开始,relativeHeadRowIndex=" + (currentRow - 1));
// 更新当前行号
currentRow += actualSize;
}
} finally {
if (excelWriter != null) {
excelWriter.finish();
}
}
}
911

被折叠的 条评论
为什么被折叠?



