Apache POI: content in excel file gets corrupted

2019-07-25 04:53发布

I am writing a method which writes to an Excel file. 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...

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

1条回答
混吃等死
2楼-- · 2019-07-25 05:27

You shouldn't append data to Excel Workbook explicitly, which also point by @Axel in his comment

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. As, you are create new Row in each call

Row row = sheet.createRow(rowNumber);
查看更多
登录 后发表回答