![](/img/trans.png)
[英]Excel file gets corrupted after overwrite in Android with apache poi
[英]Apache POI: content in excel file gets corrupted
我正在編寫一種寫入 Excel 文件的方法。 在調用之前,我創建了一個工作簿和一個工作表。 代碼執行時沒有任何錯誤,但在打開創建的 Excel 文件時,我收到消息:我們發現某些內容存在問題...
我的方法是這樣的:
public void writeToCell(int rowNumber, int cellNumber, Double content) {
Row row = sheet.createRow(rowNumber);
Cell cell = row.createCell(cellNumber);
cell.setCellValue(content);
try (FileOutputStream outputStream = new FileOutputStream(month + ".xlsx", true)) {
workbook.write(outputStream);
outputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
這就是我調用該方法的方式:
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(month);
writeToCell(25, 4, 0.0);
writeToCell(25, 6, 23.32);
您不應該明確地將數據附加到 Excel 工作簿,@Axel 在他的評論中也指出了這一點
try (FileOutputStream outputStream = new FileOutputStream(month + ".xlsx", true))
反而
try (FileOutputStream outputStream = new FileOutputStream(month + ".xlsx"))
對於旁注,
writeToCell(25, 4, 0.0);
writeToCell(25, 6, 23.32);
最后一次調用writeToCell
將覆蓋相同第 25 行的先前值。 因為,您在每次調用中創建新Row
Row row = sheet.createRow(rowNumber);
我也有那個錯誤,碰巧在某些單元格中,單元格內容類型和單元格值不匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.