简体   繁体   English

Apache POI:excel 文件中的内容已损坏

[英]Apache POI: content in excel file gets corrupted

I am writing a method which writes to an Excel file.我正在编写一种写入 Excel 文件的方法。 Before calling I create a Workbook and a Sheet.在调用之前,我创建了一个工作簿和一个工作表。 The code executes without any errors, but when opening the created Excel file I get the message: We found a problem with some content in...代码执行时没有任何错误,但在打开创建的 Excel 文件时,我收到消息:我们发现某些内容存在问题...

My method looks like this:我的方法是这样的:

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();
    }
}

This is how I call the method:这就是我调用该方法的方式:

XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(month);

writeToCell(25, 4, 0.0);
writeToCell(25, 6, 23.32);

You shouldn't append data to Excel Workbook explicitly, which also point by @Axel in his comment您不应该明确地将数据附加到 Excel 工作簿,@Axel 在他的评论中也指出了这一点

try (FileOutputStream outputStream = new FileOutputStream(month + ".xlsx", true)) 

instead反而

try (FileOutputStream outputStream = new FileOutputStream(month + ".xlsx")) 

For side note,对于旁注,

writeToCell(25, 4, 0.0);
writeToCell(25, 6, 23.32);  

Last call of writeToCell will overwrite the previous value of same 25th row.最后一次调用writeToCell将覆盖相同第 25 行的先前值。 As, you are create new Row in each call因为,您在每次调用中创建新Row

Row row = sheet.createRow(rowNumber);

我也有那个错误,碰巧在某些单元格中,单元格内容类型和单元格值不匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM