Word文档分为两种格式,.doc和OOXML规范的.docx,在poi中也有相应的类包处理。

而doc文件的格式一般都不为2003版的doc文件格式,可能为rtf、xml等格式。

Maven依赖

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-scratchpad</artifactId>
  <version>4.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>4.0.1</version>
</dependency>

 

对docx文件读取

File docFile = new File("d://a.docx");
FileInputStream fis = new FileInputStream(docFile);
XWPFDocument xdoc = new XWPFDocument(fis);
XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc);
String result = extractor.getText();
logger.info(result);

 

对docx里面图片的获取测试

try {
    File docFile = new File("d://a.docx");
    FileInputStream fis = new FileInputStream(docFile);
    XWPFDocument xdoc = new XWPFDocument(fis);
    byte[] bytes = xdoc.getAllPictures().get(0).getData();
    OutputStream os = new FileOutputStream("d://a.png");
    int len = 0;
    int count = 0;
    while (bytes.length / 4096 > count) {
        os.write(bytes, 4096 * count++, 4096);
    }
    os.close();
} catch (IOException e) {
    e.printStackTrace();
}

 

java 导入cer java 导入word_apache

 

对doc文件读取

 

File docFile = new File("d://abc.doc");
 FileInputStream fis = new FileInputStream(docFile);
 HWPFDocument doc = new HWPFDocument(fis);
 WordExtractor extractor=new WordExtractor(doc);
String result =extractor.getText();
 logger.info(result);

 

这里测试用的是网上下载的doc文件,报出该文件实际是一个rtf文件的错误,网上的文档可能大多都为使用rtf模板生成的word文档,其实该文件的实际编码格式为rtf的格式,将文件存储为rtf后缀,发现也是能够打开的。

 

java.lang.IllegalArgumentException: The document is really a RTF file
 
       at org.apache.poi.hwpf.HWPFDocumentCore.verifyAndBuildPOIFS(HWPFDocumentCore.java:126)
       at org.apache.poi.hwpf.HWPFDocument.<init>(HWPFDocument.java:165)

 

试着用rtf去解析

 

String result = null;
File file = new File("d://abc.doc");
try {
    DefaultStyledDocument dsd = new DefaultStyledDocument();
    InputStream is = new FileInputStream(file);
    new RTFEditorKit().read(is, dsd, 0);
    System.out.println(  new String(dsd.getText(0, dsd.getLength()).getBytes()));
} catch (IOException e) {
    e.printStackTrace();
} catch (BadLocationException e) {
    e.printStackTrace();
}

打印出来的是乱码

 

ÎĵµÏÂÔØÍøÊÇרҵµÄÃâ·ÑÎĵµËÑË÷ÓëÏÂÔØÍøÕ¾£¬ÌṩÐÐÒµ×ÊÁÏ£¬¿¼ÊÔ×ÊÁÏ£¬½Ìѧ¿Î¼þ£¬Ñ§ÊõÂÛÎÄ£¬¼¼Êõ×ÊÁÏ£¬Ñо¿±¨¸æ£¬¹¤×÷·¶ÎÄ£¬×ʸñ¿¼ÊÔ£¬wordÎĵµ£¬×¨ÒµÎÄÏ×£¬Ó¦ÓÃÎÄÊ飬ÐÐÒµÂÛÎĵÈÎĵµËÑË÷ÓëÎĵµÏÂÔØ£¬ÊÇÄúÎĵµÐ´×÷ºÍ²éÕҲο¼×ÊÁϵıر¸ÍøÕ¾¡£
ÎĵµÏÂÔØ
ÒÚÍòÎĵµ×ÊÁÏ£¬µÈÄãÀ´·¢ÏÖ

 

将编码转成gbk

 

new String(dsd.getText(0, dsd.getLength()).getBytes("ISO8859-1"),"GBK")

 

正常解析

java 导入cer java 导入word_apache_02

将文件格式转为97-2003版的doc文件

使用WordExtractor去解析可以了,所以在解析的时候也主要是看文档的实际格式为什么格式,而后缀为doc的实际文件格式也可以有很多种,如doc,xml,rtf等。在读取时也要有多种解析方式。