Apache POI: content in excel file gets corrupted

2019-07-25 04:55发布

问题:

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:

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