写入后Excel文件损坏 [英] Excel file corrupt after writing

查看:98
本文介绍了写入后Excel文件损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用3.10版本的POI.我遇到的问题是我正在创建一个xls,xlsx文件.写入文件时一切看起来不错.大约2MB.当我在excel中打开文件时,它会将文件截断为4K,而我只得到了列标题,所有数据都消失了.如果我尝试以xlsx格式打开,则表示它已损坏.其他人遇到了这个问题.

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.

这是写数据行的代码.

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

推荐答案

您似乎每行写一次文件,这不是您想要的.完成后,您只应在最后写出工作簿

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

这篇关于写入后Excel文件损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆