Excel file corrupt after writing

只愿长相守 提交于 2019-12-11 06:24:54

问题


I am using the 3.10 Version of POI. Problem I am running into is that I am creating a xls,xlsx file. All looks good when writing the file. It is about 2MB. When I open in excel it truncates the file to 4K and I only get my column headers all the data is gone. If I try to open as xlsx it says it is corrupt. Anyone else hit this problem.

Here is the code that writes the row of data.

public void writeRow(int irow, String[] rdata) {
    Row row;
    Cell cell;
    int cellnum = 0;
    int rownum = irow;

    System.out.println("writeRow():ROW -> " + irow);
    row = _wSheet.getRow(irow);

    if (row == null) {
        System.out.println("writeRow():Creating Row " + irow);
        row = _wSheet.createRow(rownum);
    }

    for (String rdata1 : rdata) {
        cell = row.createCell(cellnum++);
        cell.setCellValue((String) rdata1);
    }
    write();
}

public void write() {
    try {
        _gWorkbook.write(_outF);
        _outF.flush();
    } catch (IOException wbe) {
        System.out.println("write(): Error writing workbook "+wbe.getMessage());
    }
}

回答1:


You appear to be writing the file out once per row, which isn't what you want to do. You should only write the workbook out at the very end, when you're done

So, to fix it, change your code so that you only call Workbook.write(OutputStream) at the very end of your code. Don't try to do it as you go, the file format doesn't work like that



来源:https://stackoverflow.com/questions/26318638/excel-file-corrupt-after-writing

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