Excel file corrupt after writing

2019-08-10 21:13发布

问题:

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