簡體   English   中英

使用 apache poi 在 Android 中覆蓋后 Excel 文件被損壞

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

我想覆蓋一個 excel 文件,但覆蓋的文件已損壞。 我正在使用 android studio,我想將信息保存到單個 excel 文件中。 下面是我的代碼:

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

我在 pc 上用 excel 文件測試了這段代碼並且運行良好,但是在 android 中文件被損壞了。

Apache POI 不完全支持您嘗試的方式就地寫入更改的文件。

有關於通過新的 write() 方法提供此功能的討論,但目前您需要寫入不同的文件以避免在關閉對象期間損壞內容。 工作簿關閉后,如有必要,您可以將新文件移到舊文件上。

請參閱一些相關討論此錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM