ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

如何摆脱使用Apache POI XSSF创建的xlsx文件中的“保存更改?”提示

2019-10-08 15:02:41  阅读:243  来源: 互联网

标签:xlsx java xssf


打开并立即关闭使用Apache POI XSSF创建的xlsx文件后,系统会提示我保存未保存的更改.据我所知,这种情况正在发生,因为我在xlsx文件中使用公式.

根据javadoc,这应该通过设置XSSFWorkbook.setForceFormulaRecalculation(true)来绕过
但是,这并没有解决问题.

我还尝试在保存文件之前手动重新计算公式,但没有成功.

SSCCE:

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class XSSFExample {

    public static void main(String[] args) {
        // Create workbook and sheet
        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("Sheet 1");

        // Create a row and put some cells in it.
        Row row = sheet.createRow((short) 0);
        row.createCell(0).setCellValue(5.0);
        row.createCell(1).setCellValue(5.0);
        row.createCell(2).setCellFormula("A1/B1");


        // Write the output to a file
        try (FileOutputStream fileOut = new FileOutputStream("XSSFExample.xlsx")) {
            wb.setForceFormulaRecalculation(false);
            System.out.println(wb.getForceFormulaRecalculation()); // prints "false"
            XSSFFormulaEvaluator.evaluateAllFormulaCells((XSSFWorkbook) wb); // this doesn't seem to make any difference
            wb.write(fileOut);
        } catch (IOException ex) {
            Logger.getLogger(XSSFExample.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

在第一次打开文件后,我该怎么办才能创建文件而不会提示保存文件?

更新:
here (https://poi.apache.org/spreadsheet/eval.html#recalculation)所述,我还尝试了另一种方法来手动重新计算,但没有成功.即使在保存后重新读取文件,重新计算并另存为第二个文件也不起作用.

更新2:
考虑到已接受的答案,我能够通过在上面的SSCCE中添加以下代码行来解决问题:
(请注意,这只是解决问题的“快速而肮脏”尝试.可能有很多改进).

ZipFile zipFile = new ZipFile("XSSFExample.xlsx");
final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("XSSFExample_NoSave.xlsx"));
for (Enumeration e = zipFile.entries(); e.hasMoreElements();) {
    ZipEntry entryIn = (ZipEntry) e.nextElement();
    if (!entryIn.getName().equalsIgnoreCase("xl/workbook.xml")) {
        zos.putNextEntry(entryIn);
        InputStream is = zipFile.getInputStream(entryIn);
        byte[] buf = new byte[1024];
        int len;
        while ((len = (is.read(buf))) > 0) {
            zos.write(buf, 0, len);
        }
    } else {
        zos.putNextEntry(new ZipEntry("xl/workbook.xml"));
        InputStream is = zipFile.getInputStream(entryIn);
        byte[] buf = new byte[1024];
        int len;
        while (is.read(buf) > 0) {
            String s = new String(buf);
            String searchFileVersion = "/relationships\"><workbookPr";
            String replaceFileVersion = "/relationships\"><fileVersion appName=\"xl\" lastEdited=\"5\" lowestEdited=\"5\" rupBuild=\"9303\"/><workbookPr";
            String searchCalcId = "<calcPr calcId=\"0\"/>";
            String replaceCalcId = "<calcPr calcId=\"" + String.valueOf(Integer.MAX_VALUE) + "\"/>";
            if (s.contains(searchFileVersion)) {
                s = s.replaceAll(searchFileVersion, replaceFileVersion);
            }
            if (s.contains(searchCalcId)) {
                s = s.replaceAll(searchCalcId, replaceCalcId);
            }
            len = s.trim().length();
            buf = s.getBytes();
            zos.write(buf, 0, (len < buf.length) ? len : buf.length);
        }
    }
    zos.closeEntry();
}
zos.close();

解决方法:

问题

问题可能在于MS Excel本身(一旦确定所有公式都已计算并保存在.xlsx文件中).根据我的测试,Excel将在打开期间重新计算所有公式,如果它发现该文件是由旧版本的Excel或其他应用程序上次保存的(关键是版本号不匹配和/或低于当前版本Excel打开文件)以保持良好的兼容性.

(使Excel认为.xlsx文件是由相同的Excel版本生成的,以避免重新计算)

Excel从位于.xlsx存档内的xl目录中的workbook.xml文件中读取所有文件版本控制信息(.xlsx只是一个压缩存档).

Apache POI生成的workbook.xml文件可能如下所示:

<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
  <workbookPr date1904="false"/>
  <bookViews><workbookView activeTab="0"/></bookViews>
  <sheets>
    <sheet name="new sheet" r:id="rId3" sheetId="1"/>
  </sheets>
  <calcPr calcId="0"/>
</workbook>

Excel 2010生成的文件如下所示:

<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
  <fileVersion appName="xl" lastEdited="5" lowestEdited="5" rupBuild="9303"/>
  <workbookPr defaultThemeVersion="124226"/>
  <bookViews><workbookView xWindow="630" yWindow="510" windowWidth="27495" windowHeight="14505"/></bookViews>
  <sheets>
    <sheet name="new sheet" sheetId="1" r:id="rId1"/>
  </sheets>
  <calcPr calcId="145621"/>
</workbook>

注意< fileVersion> POI生成的文件中的标记完全丢失,< calcPr>标记与calcId在Excel生成的文件中设置为某个实际值.

我通过插入相关的< fileVersion>来避免Excel 2010自动公式重新计算(以及恼人的“保存更改”对话框).将calcId标记并设置为等于或大于我当前版本的Excel生成的数字到POI生成的workbook.xml的数字.

有关workbook.xml格式的更多信息,请参见MSDN Open XML SDK documentation.

标签:xlsx,java,xssf
来源: https://codeday.me/bug/20191008/1872548.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有