4

I have a Microsoft Word .docx document uploaded to Sharepoint. In my java code, I have downloaded this document into a byte[]. Ok. Now, what I want is to process this byte[] to obtain an XWPFDocument and be able to replace some variables into the document.

Please, could anybody help me?

Thanks!!

user3270931
  • 43
  • 1
  • 5

2 Answers2

6

You can read as XWPFDocument from byte[] by using InputStream(ByteArrayInputStream) specified in the constructor of XWPFDocument and you can get paragraphs and runs from XWPFDocument. After that you can edit like below.

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);
riversun
  • 758
  • 8
  • 12
1
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

kuhajeyan
  • 10,727
  • 10
  • 46
  • 71
  • Thank you. It works for me with the second solution.This way gives me the following error: javax.el.ELException: java.lang.NoSuchMethodError: org.apache.xmlbeans.XmlOptions.setLoadEntityBytesLimit(I)Lorg/apache/xmlbeans/XmlOptions; I think it was because a library version problem. Thanks again. – user3270931 Sep 30 '16 at 08:07