转载自罗刚老师的《解密搜索引擎技术实战》电子工业出版社
Word是微软公司开发的字处理文件格式,以“doc”或者“docx”作为文件后缀名。Apache的POI(http://poi.apache.org/)可以用来在Windows或Linux平台下提取Word文档。用POI提取文本的基本方法如下:
public static String readDoc(InputStream is) throws IOException{
//创建WordExtractor
WordExtractor extractor=new WordExtractor(is);
// 对DOC文件进行提取
return extractor.getText();
}
为了提取Word文档的标题,需要深入了解POI接口。一个Word文档包含一个或者多个Section,每个Section下面包含一个或者多个Paragraph,每个Paragrah下面包含一个或者多个CharacterRun。
图3-16 Word文档结构图
遍历Word文档结构的代码如下:
Range r = doc.getRange();
for (int x = 0; x < r.numSections(); x++) {
Section s = r.getSection(x);
for (int y = 0; y < s.numParagraphs(); y++) {
Paragraph p = s.getParagraph(y);
for (int z = 0; z < p.numCharacterRuns(); z++) {
CharacterRun run = p.getCharacterRun(z);
//字符串文本
String text = run.text();
System.out.println(text);
}
}
}
标题往往是居中对齐的。可以通过Paragraph的getJustification方法得到段落的对齐方式。getJustification的返回值0表示左对齐,1表示居中对齐,2表示右对齐,3表示两端对齐。
可以通过CharacterRun对象取得文字内容、字体大小、文字颜色等信息。
run.text(); //文字内容
run.getFontSize(); //字体大小
run.getColor(); //文字颜色
对于Word 95这样的老版本,需要使用Word6Extractor,例如:
Word6Extractor extractor = new Word6Extractor(in);
String text = extractor.getText();
读入文档表格中的内容:
FileInputStream in = new FileInputStream("d:\\test.doc");
POIFSFileSystem pfs = new POIFSFileSystem(in);
HWPFDocument hwpf = new HWPFDocument(pfs);
Range range = hwpf.getRange();
TableIterator it = new TableIterator(range);
while (it.hasNext()) { //看有没有下一个表格
Table tb = (Table) it.next(); //取得下一个表格
for (int i = 0; i < tb.numRows(); i++) {
TableRow tr = tb.getRow(i);
for (int j = 0; j < tr.numCells(); j++) {
TableCell td = tr.getCell(j);
for (int k = 0; k < td.numParagraphs(); k++) {
Paragraph p = td.getParagraph(k);
String s = p.text();
System.out.println(s);
}
}
}
}