How to get rid of “Save changes?” prompt on xlsx-files created with Apache POI XSSF

后端 未结 2 1874
夕颜
夕颜 2021-01-14 09:10

After opening and immediately closing an xlsx-file, created with Apache POI XSSF, I get prompted to save unsaved changes. As far as i can tell, this is happening because I a

相关标签:
2条回答
  • 2021-01-14 09:31

    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.

    SOLUTION

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

    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 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>
    

    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>
    

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

    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.

    More information regarding the workbook.xml format can be found on MSDN Open XML SDK documentation.

    0 讨论(0)
  • 2021-01-14 09:43

    Even I was facing the same issue but after adding the below line, the issue has been resolved.

    wb.getCreationHelper().createFormulaEvaluator().evaluateAll();
    
    0 讨论(0)
提交回复
热议问题