简体   繁体   English

使用 apache poi 在 Android 中覆盖后 Excel 文件被损坏

[英]Excel file gets corrupted after overwrite in Android with apache poi

I want to overwrite an excel file, but the overwritten file gets corrupted.我想覆盖一个 excel 文件,但覆盖的文件已损坏。 I am working with android studio and I want to save information into single excel file.我正在使用 android studio,我想将信息保存到单个 excel 文件中。 Below is my code:下面是我的代码:

private void saveIntoExcel(String fileName, String[] data) {
    try {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + getString(R.string.app_name) + "/" + fileName;

        InputStream inp = new FileInputStream(new File(path));

        HSSFWorkbook workbook = new HSSFWorkbook(inp);
        HSSFSheet sheet = workbook.getSheetAt(0);
        HSSFRow row;

        row = sheet.createRow(sheet.getLastRowNum() + 1);
        for (int i = 0; i < data.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(data[i]);
        }

        FileOutputStream fos = null;
        File file;

        file = new File(path);
        fos = new FileOutputStream(file);

        workbook.write(fos);
        fos.close();        

        showToast(str_success);
    } catch (Exception e) {
        showToast(e.getMessage());
    }
}

I tested this code with excel files on pc and works perfectly, but in android the files gets corrupted.我在 pc 上用 excel 文件测试了这段代码并且运行良好,但是在 android 中文件被损坏了。

Apache POI does not fully support in-place writing of the changed file the way you try to do it. Apache POI 不完全支持您尝试的方式就地写入更改的文件。

There is discussion about providing this via a new write() method, but currently you will need to write to a different file to avoid corrupting things during closing the objects.有关于通过新的 write() 方法提供此功能的讨论,但目前您需要写入不同的文件以避免在关闭对象期间损坏内容。 After the workbook is closed you can move the new file over the old one if necessary.工作簿关闭后,如有必要,您可以将新文件移到旧文件上。

See some related discussion and this bug .请参阅一些相关讨论此错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM