Apache POI: content in excel file gets corrupted

时光毁灭记忆、已成空白 提交于 2019-12-24 09:36:36

问题


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


来源:https://stackoverflow.com/questions/48024118/apache-poi-content-in-excel-file-gets-corrupted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!