2015-10-20 145 views
1

我使用Apache POI创建一个.docx文件用下面的代码:的Java:XWPFWordExtractor.getText()抛出NullPointerException异常

XWPFDocument document = new XWPFDocument(); 
XWPFParagraph paragraph = document.createParagraph(); 
XWPFRun run = paragraph.createRun(); 
run.setText(text); 
String filePath = outputPathWithoutExtension + ".docx"; 
try { 
    FileOutputStream stream = new FileOutputStream(new File(filePath)); 
    document.write(stream); 
    stream.close(); 
} catch (IOException exception) { 
    LOGGER.error("Could not create file '{}'", filePath); 
} 

,然后我尝试用下面的代码来阅读:

FileInputStream fileStream = new FileInputStream(filePath); 
try { 
    XWPFDocument docx = new XWPFDocument(fileStream); 
    XWPFWordExtractor wordExtractor = new XWPFWordExtractor(docx); 
    text = wordExtractor.getText(); 
} catch (IOException | POIXMLException | OfficeXmlFileException 
      | NullPointerException exception) { 
    LOGGER.error("Could not load file - Exception: {}", exception.getMessage()); 
} 

在哪里我打电话getText()行,它抛出一个NullPointerException

java.lang.NullPointerException 
at org.apache.poi.xwpf.extractor.XWPFWordExtractor.extractHeaders(XWPFWordExtractor.java:162) 
at org.apache.poi.xwpf.extractor.XWPFWordExtractor.getText(XWPFWordExtractor.java:87) 

这个问题似乎是extractText调用extractHeadersXWPFHeaderFooterPolicy的文件...在我的情况是空的。当它试图在第一线使用它时......繁荣。

我试图创建自己的“页眉/页脚政策”,例如:

try { 
    new XWPFHeaderFooterPolicy(document); 
} catch (IOException | XmlException exception) { 
    LOGGER.warn("Could not create output document header - " 
      + "document might not be readable in all readers"); 
} 

然而,这本身将引发NullPointerException,因为它试图通过doc.getDocument().getBody().getSectPr()访问“SectPr”的文件,它返回null ...然后第一次使用那个......繁荣。

所以,我的问题是:我显然没有正确创建XWPFDocument ...有人可以让我平直吗?

备注:如果我在Word中打开文件,文件看起来很好。如果在创建和读取文件之间,我打开它,编辑它,保存并关闭它,然后getText()的调用按预期执行,没有NullPointerException。 Word必须在保存时填写适当的页眉/页脚策略。

+0

看起来是一个错误 - 你尝试报告为一个bug为[Apache的POI bug跟踪系统(https://开头BZ。 apache.org/bugzilla/enter_bug.cgi?product=POI)? – Gagravarr

回答

0

啊哈!我在这里找到了我的答案:How to create a header/footer in new docx document?

我基本上刚刚放弃了一步。将此代码添加到文档创建中的允许它读取:

// Add a SectPr and header/footer policy so document can be opened and read by POI 
try { 
    document.getDocument().getBody().addNewSectPr(); 
    new XWPFHeaderFooterPolicy(document); 
} catch (IOException | XmlException exception) { 
    LOGGER.warn("Could not create output document header - " 
      + "document might not be readable in all readers"); 
} 
相关问题