且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-04-29 23:09:29

问题



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

PROBLEM

The problem could lie in MS Excel itself (once you are sure that all formulas were calculated and saved in the .xlsx file). According to my testing, Excel will recalculate all formulas during opening if it finds out that the file was last saved by older version of Excel or other application (the point is that the version numbers doesn't match and/or are lower than current version of Excel opening the file) to maintain good compatibility.

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

(making Excel think that the .xlsx file was generated by the same Excel version to avoid recalculation)

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

Excel reads all file versioning info from workbook.xml file located in xl directory inside .xlsx archive (.xlsx is just a zipped archive).

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

workbook.xml file generated by Apache POI could look like this:

<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生成的文件如下所示:

The file generated by Excel 2010 looks like this:

<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生成的文件中设置为某个实际值。

Notice the <fileVersion> tag completely missing in POI generated file and <calcPr> tag with calcId set to some real value in Excel generated file.

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

I was able to avoid Excel 2010 automatic formula recalculation (and annoying "Save changes" dialog) by inserting correlated <fileVersion> tag and setting calcId to equal or greater number than the number generated by my current version of Excel to the workbook.xml generated by POI.

有关 workbook.xml的更多信息格式可以在 MSDN上找到打开XML SDK文档