魂心

poi读取word的内容

pache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。

1.读取word 2003及word 2007需要的jar包

  读取 2003 版本(.doc)的word文件相对来说比较简单,只需要 poi-3.5-beta6-20090622.jar 和 poi-scratchpad-3.5-beta6-20090622.jar 两个 jar 包即可, 而 2007 版本(.docx)就麻烦多,我说的这个麻烦不是我们写代码的时候麻烦,是要导入的 jar 包比较的多,有如下 7 个之多:
 1. openxml4j-bin-beta.jar
 2. poi-3.5-beta6-20090622.jar
 3. poi-ooxml-3.5-beta6-20090622.jar
 4 .dom4j-1.6.1.jar
 5. geronimo-stax-api_1.0_spec-1.0.jar
 6. ooxml-schemas-1.0.jar
 7. xmlbeans-2.3.0.jar
其中 4-7 是 poi-ooxml-3.5-beta6-20090622.jar 所依赖的 jar 包(在 poi-bin-3.5-beta6-20090622.tar.gz 中的 ooxml-lib 目录下可以找到)。

2.读取.doc的word的文档

public static String readDoc(File file) {

System.out.println(file.getAbsolutePath() + "....doc");
String text = "";
FileInputStream in;
try {
in = new FileInputStream(file);
WordExtractor extractor = new WordExtractor(in);
text = extractor.getText();
in.close();
} catch (Exception e) {
System.out.println("Word解析错误!");
}
return text;

}

3、读取.docx的word的文档

public static String readDocx(File file) {
System.out.println(file.getAbsolutePath() + "....docx");
String str = "";
try {
FileInputStream fis = new FileInputStream(file);
XWPFDocument xdoc = new XWPFDocument(fis);
XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc);
str = extractor.getText();
System.out.println(str);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}

return str;

}

posted on 2017-05-25 14:24  魂心  阅读(720)  评论(0编辑  收藏  举报