【问题标题】:Change a value in embedded xlsx with apache poi使用 apache poi 更改嵌入式 xlsx 中的值
【发布时间】:2016-01-25 18:21:22
【问题描述】:

我尝试使用 apache poi 更改嵌入在 docx 文件中的 xlsx 文件的值。可悲的是,我还没有找到解决这个问题的合适方法。运行我的程序后,新创建的带有嵌入式 xlsx 表的 docx 文件没有改变。 到目前为止,这是我尝试过的:

 FileInputStream fis = new FileInputStream("old.docx");
 XWPFDocument xdoc = new XWPFDocument(OPCPackage.open(fis));
     System.out.println(xdoc.getAllEmbedds().get(0));
     File file2 = new File("new.docx");
     
     for (PackagePart pPart : xdoc.getAllEmbedds()) {
        String contentType = pPart.getContentType();
       
        // Excel Workbook - OpenXML file format
        if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
            XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(pPart.getInputStream());
            XSSFSheet sheet = embeddedWorkbook.getSheetAt(0);
            sheet.getRow(1).getCell(1).setCellValue("someValue"); //change value here
            embeddedWorkbook.write(pPart.getOutputStream());
        }
    }
    xdoc.write(new FileOutputStream(file2));

知道如何解决这个问题吗?

【问题讨论】:

  • 如果跳过 XWPF 部分,只在 OPCPackage 级别工作会发生什么?

标签: java excel ms-word apache-poi docx


【解决方案1】:

我不相信这会在满足所有愿望的情况下成为可能。实际上,嵌入的XSSFWorkbook 已更新。但是,如果您打开new.docx,看到的不是XSSFWorkbook,而是EMF 的图片。此图片只有在双击打开嵌入的XSSFWorkbook,然后在外部单击再次关闭时才会更新。

如果EMF 图片实际上不在ZIP 存档中,则其他一些帖子建议在打开Word 文件时更新它。但它不会。

试试:

  for (PackagePart pPart : xdoc.getPackage().getPartsByName(Pattern.compile(".*emf$"))) {
    System.out.println(pPart.getPartName());
    //xdoc.getPackage().removePartRecursive(pPart.getPartName());
    xdoc.getPackage().removePart(pPart.getPartName());
  }

所以“解决方案”是,从更新的XSSFWorkbook 中新建一个EMF 快照图片,并用这张新图片替换旧的EMF 图片。在我看来不太可能。

如果嵌入的XSSFWorkbook 关闭,创建EMF 快照图片的程序例程似乎是Word 应用程序的一部分。但直到现在它还不是apache-poi 的一部分。当然,它不是XML 程序例程的一部分。

【讨论】:

    【解决方案2】:

    在保存文档之前设置:

    // ask user to refresh fields upon opening the document
    document.enforceUpdateFields();
    

    当用户打开文件并通过单击“是”接受字段更新时,为我更新 Excel 预览图像。

    【讨论】:

      猜你喜欢
      • 2019-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-14
      • 1970-01-01
      相关资源
      最近更新 更多