首页 > 解决方案 > Java Apache POI - 编辑和保存后需要修复工作簿

问题描述

我的大部分 Java 程序都处理 Excel 和 Apache POI。但是,一种方法似乎会损坏文件,迫使用户在打开之前对其进行修复。尝试打开时的 Excel 消息是:“我们发现 [工作簿] 中的某些内容存在问题。您希望我们尽可能多地恢复吗?如果您信任此工作簿的来源,请单击是。”

事实上,我用另一种方法编辑了这个确切的工作簿,没有任何问题。据我所知,在这段看似错误的代码中,我没有做任何我以前没有做过的事情。

public static void refreshExcel() {
try {
    workbook = new XSSFWorkbook(new BufferedInputStream(new FileInputStream(file)));
    sheet = workbook.getSheet("DISTRIBUTION");
} catch (Exception ex) {
    MasterLog.appendError(ex);
}//try-catch                                                                                                               
sheet.disableLocking();

//you can ignore the next 3 lines, they essentially find the rows that need to be updated
ArrayList<String> list = Log.modelLackingSCs();
for (String sc : list) {
    int desiredIndex = findFirstIndex(sc);

    XSSFRow row = sheet.getRow(desiredIndex);
    try {
        while (row.getCell(10).getNumericCellValue() == Integer.parseInt(sc)) {
            row.createCell(8).setCellValue(OrderLog.findShipDate(OrderLog.getWB(sc)));
            row = sheet.getRow(++desiredIndex);
        }//while                                                                                                           
    } catch (IllegalStateException ise) {
        MasterLog.appendEntry("ise");
    } catch (Exception ex) {
        MasterLog.appendError(ex);
    }//try-catch                                                                                                           
}//for                                                                                                                     
sheet.enableLocking();

try {
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
    workbook.write(bos);
} catch (Exception ex) {
    MasterLog.appendError(ex);
}//try-catch                                                                                                               
}//refreshExcel()

标签: javaexcelapache-poi

解决方案


推荐阅读