問題
業(yè)務中需要往給定格式的excel中寫入數(shù)據(jù)。
使用shiftRows函數(shù)往excel中插入新行時,xls文件沒問題,xlsx文件問題多多
- 執(zhí)行如下代碼,xls格式插入了3行,xlsx格式卻只插入了2行
- xlsx執(zhí)行shiftRows操作之后,合并單元格丟失
- xlsx執(zhí)行shiftRows操作之后,用excel打開提示格式有問題,用wps打開正常
InputStream inp = new FileInputStream("/Users/shao/Downloads/模板.xlsx");
Workbook templateWorkbook = WorkbookFactory.create(inp);
Sheet sheet = templateWorkBook.getSheetAt(0);
sheet.shiftRows(5, sheet.getLastRowNum(), 1);
sheet.shiftRows(5, sheet.getLastRowNum(), 1);
sheet.shiftRows(5, sheet.getLastRowNum(), 1);
OutputStream outputStream = new FileOutputStream("/Users/shao/Downloads/模板輸出.xlsx");
templateWorkbook.write(outputStream);
解決
poi 4.1.1版本修復了該bug,升級到最新的4.1.2,問題解決
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
原因
poi bug
參考
https://stackoverflow.com/questions/55980407/apache-poi-shiftrows-corrupts-file-and-deletes-content
http://poi.apache.org/changes.html
image.png
