1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
| /**
* 测试导出 excel
* @author jamesaks
* @since 2025/10/25
*/
@Slf4j
@SpringBootTest(classes = MaterialApplication.class)
public class TestExportExcelStyle {
public void reportExport(ExcelTemplate template) {
// 2. 文件路径
String filePath = "/Users/jamesaks/Downloads/excel-test/" + System.currentTimeMillis() + ".xlsx";
File file = new File(filePath);
if (!file.getParentFile().exists()) {
boolean mkdirSuccess = file.getParentFile().mkdirs();
if (!mkdirSuccess) {
throw new RuntimeException("创建目录失败");
}
}
// 3. 写文件(注册样式)
try (ExcelWriter writer = EasyExcel.write(file).build()) {
// 1. 检查数据
template.checkIsEmpty();
//写入
WriteSheet sheet = template
.getSheetBuilder(EasyExcel.writerSheet(template.sheetName()))
.useDefaultStyle(false)
.needHead(true)
.head(template.getHead())
.build();
//区分 Table 和 sheet 概念
writer.write(template.getBody(), sheet);
}
}
@Test
void exportExcel() {
reportExport(new ExcelTemplate() {
@Override
public String sheetName() {
return "测试";
}
@Override
public List<List<ExcelCell>> rows() {
//外层为一行
//内层为每行的列数
return List.of(
List.of(new ExcelCell(3), new ExcelCell(4), new ExcelCell("=SUM(A2:B2)"), new ExcelCell("=A2-B2")),
List.of(new ExcelCell(100), new ExcelCell(200), new ExcelCell("=SUM(A3:B3)"), new ExcelCell("=A3-B3"))
);
}
@Override
public List<List<ExcelCell>> head() {
//外层表达每行列数
//内层为有几行
return List.of(
List.of(new ExcelCell("数值1")),
List.of(new ExcelCell("数值2")),
List.of(new ExcelCell("相加")),
List.of(new ExcelCell("相减"))
);
}
@Override
public ExcelWriterSheetBuilder getSheetBuilder(ExcelWriterSheetBuilder writerBuilder) {
//实现公式自动相加的核心逻辑
return writerBuilder.registerWriteHandler(new CellWriteHandler() {
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
if (!isHead && CellType.STRING.equals(cell.getCellType()) && cell.getStringCellValue().contains("=")) {
cell.setCellFormula(cell.getStringCellValue().substring(1));
}
if (StrUtil.isNumeric(cell.getStringCellValue())) {
//将字符串转为数值类型
cell.setCellValue(Integer.parseInt(cell.getStringCellValue()));
}
}
});
}
});
log.info("生成成功");
}
}
|