【问题标题】:How can I create a XWPFDocument from a byte[]?如何从 byte[] 创建 XWPFDocument?
【发布时间】:2016-09-29 21:36:31
【问题描述】:

我有一个 Microsoft Word .docx 文档上传到 Sharepoint。在我的 java 代码中,我已将此文档下载到 byte[] 中。好的。现在,我想要处理这个 byte[] 以获得 XWPFDocument 并能够将一些变量替换到文档中。

请问有人可以帮我吗?

谢谢!!

【问题讨论】:

    标签: java xwpf


    【解决方案1】:

    您可以使用 XWPFDocument 的构造函数中指定的 InputStream(ByteArrayInputStream) 从 byte[] 中读取为 XWPFDocument,并且可以从 XWPFDocument 中获取段落和运行。 之后,您可以像下面这样进行编辑。

    byte[] byteData = ....
    
    // read as XWPFDocument from byte[]
    XWPFDocument doc = new XWPFDocument(new ByteArrayInputStream(byteData));
    
    int numberToPrint = 0;
    
    // you can edit paragraphs
    for (XWPFParagraph para : doc.getParagraphs()) {
        List<XWPFRun> runs = para.getRuns();
    
        numberToPrint++;
    
        for (XWPFRun run : runs) {
    
            // read text
            String text = run.getText(0);
    
            // edit text and update it
            run.setText(numberToPrint + " " + text, 0);
        }
    }
    
    // save it and you can get the updated .docx
    FileOutputStream fos = new FileOutputStream(new File("updated.docx"));
    doc.write(fos);
    

    【讨论】:

      【解决方案2】:
      ByteArrayInputStream bis = new ByteArrayInputStream(bytebuffer);
      POIXMLTextExtractor extractor = (POIXMLTextExtractor) ExtractorFactory.createExtractor(bis);
      POIXMLDocument document = extractor.getDocument();
      
       if (document instanceof XWPFDocument) 
              XWPFDocument xDocument = (XWPFDocument) document;
      

      https://poi.apache.org/text-extraction.html

      【讨论】:

      • 谢谢。它适用于我的第二种解决方案。这种方式给我以下错误:javax.el.E​​LException: java.lang.NoSuchMethodError: org.apache.xmlbeans.XmlOptions.setLoadEntityBytesLimit(I)Lorg/apache/xmlbeans/XmlOptions;我认为这是因为库版本问题。再次感谢。
      猜你喜欢
      • 1970-01-01
      • 2010-12-06
      • 2012-01-11
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多