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

查看:43
本文介绍了写入后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.

这是写入数据行的代码.

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

推荐答案

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

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

因此,要修复它,请更改您的代码,以便您只调用 Workbook.write(OutputStream) 在代码的最后.不要随便尝试,文件格式不是这样的

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天全站免登陆