8
触发场景描述
如果文件不存在,则新建文件,添加第一个sheet页;否则,在该文件中追加sheet页
触发Bug的代码// 核心代码
public static <E> void writeModelList(File outputFile, List<E> modelList, int sheetNo, String sheetName) {
if (CollectionUtils.isEmpty(modelList)) {
return;
}
Class<?> clazz = modelList.get(0).getClass();
List<ReadSheet> sheets = Collections.emptyList();
boolean isAppend = false;
if (outputFile.exists()) {
isAppend = true;
ExcelReader excelReader = EasyExcel.read(outputFile).build();
sheets = excelReader.excelExecutor().sheetList();
excelReader.close();
}
if (sheets.size() > sheetNo) {
throw new G4cException(String.format(Locale.ROOT, "Invalid sheetNo,must less than or equal %d", sheets.size()));
}
if (sheets.stream().anyMatch(st -> st.getSheetName().equalsIgnoreCase(sheetName))) {
throw new G4cException(String.format(Locale.ROOT, "Sheet name %s already exists.", sheetName));
}
if (sheets.size() < sheetNo) {
sheetNo = sheets.size();
}
try (OutputStream outputStream = new FileOutputStream(outputFile, isAppend);
ExcelWriter excelWriter = EasyExcel.write(outputStream, clazz).build()) {
int pageCount = modelList.size() / PAGE_SIZE + 1;
WriteSheet writeSheet = EasyExcel.writerSheet(sheetNo, sheetName).build();
for (int i = 0; i < pageCount; i++) {
List<E> pageData = modelList.stream().skip(i * PAGE_SIZE).limit(PAGE_SIZE).collect(Collectors.toList());
excelWriter.write(pageData, writeSheet);
}
excelWriter.finish();
} catch (Exception exception) {
log.error("writeModelList=>{}", exception.getMessage());
}
}
// UT代码
@Data
@AllArgsConstructor
class DemoData {
private int num;
private String text;
}
@Test
void writeModelList() {
File outFile = new File("D:\\temp\\test.xlsx");
List<DemoData> list = new ArrayList<>(5550);
for (int i = 0; i < 5550; i++) {
DemoData demoData = new DemoData(i + 1, "data" + (i + 1));
list.add(demoData);
}
ExcelUtil.writeModelList(outFile, list, 2, "我的sheet1");
}
提示的异常或者没有达到的效果
第一次创建文件成功,
第二次追加时,文件尺寸变为之前的2倍,符合预期,但是文件打不开。UT中代码中修改sheet页ExcelUtil.writeModelList(outFile, list, 2, "我的sheet2");
,
打开时出现如下提示:
可见文件破损,修复之后,还是只有追加之前的内容,追加的内容看不到。