2016-09-29 5 views
1

У меня есть документ Microsoft Word .docx, загруженный в Sharepoint. В моем java-коде я загрузил этот документ в байт []. ОК. Теперь я хочу обработать этот байт [], чтобы получить XWPFDocument и иметь возможность заменить некоторые переменные в документе.Как создать XWPFDocument из байта []?

Возможно, кто-нибудь может мне помочь?

Спасибо!

ответ

1

Вы можете прочитать, как XWPFDocument из байта [] с помощью InputStream (ByteArrayInputStream), указанный в конструкторе 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); 
+0

Большое спасибо! Он отлично работает! – user3270931

0
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

+0

спасибо. Это работает для меня со вторым решением. Этот способ дает мне следующую ошибку: javax.el.ELException: java.lang.NoSuchMethodError: org.apache.xmlbeans.XmlOptions.setLoadEntityBytesLimit (I) Lorg/apache/xmlbeans/XmlOptions; Я думаю, это было из-за проблемы с библиотечной версией. Еще раз спасибо. – user3270931