通過使用Java POI來提取Word(1992)文檔中的表格信息,其中POI支持不同的ms文檔類型,在具體操作中需要注意。本文主要是通過POI來提取微軟2003文檔中的表格信息,具體code如下(事先需要導入POI的jar包):
public static void testWord2() {
try {
FileInputStream in = new FileInputStream("july 2005 1.doc");// 載入文檔
// FileInputStream in = new FileInputStream("2003.doc");// 載入文檔
POIFSFileSystem pfs = new POIFSFileSystem(in);
HWPFDocument hwpf = new HWPFDocument(pfs);
Range range = hwpf.getRange();// 得到文檔的讀取范圍
TableIterator it = new TableIterator(range);
FileWriter fileWriter = new FileWriter(new File("result.txt"));
// 迭代文檔中的表格
while (it.hasNext()) {
Table tb = (Table) it.next();
// 迭代行,默認從0開始
if(tb.numRows()>0) {
TableRow tr = tb.getRow(0);
// 迭代列,默認從0開始
if(tr.numCells()==2) {
TableCell td1 = tr.getCell(0);// 取得單元格
TableCell td2 = tr.getCell(1);// 取得單元格
// 取得單元格的內容
String str1 = td1.text().trim();
String str2 = td2.text().trim();
if(str2!=null&&!"".equals(str2)&&str2.contains("[21][11]")){
System.out.println(str1);
fileWriter.write(str2+"\n");
}
} else if(tr.numCells()==3){
TableCell td2 = tr.getCell(1);
String str2 = td2.text().trim();
System.out.println("str2="+str2);
fileWriter.write(str2+"\n");
}
} // end for
} // end while
fileWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
上面code只是簡單的對POI提取Word文檔中的表格信息進行測試,直接調用該方法即可。
