java表格选中_使用Java POI来选择提取Word文档中的表格信息

通过使用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文档中的表格信息进行测试,直接调用该方法即可。


版权声明:本文为weixin_34175919原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。