WORD的POI处理与原理

1 篇文章 0 订阅

转载自罗刚老师的《解密搜索引擎技术实战》电子工业出版社

 

Word是微软公司开发的字处理文件格式,以“doc”或者“docx”作为文件后缀名。ApachePOI(http://poi.apache.org/)可以用来在WindowsLinux平台下提取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);

              }

       }

}

       标题往往是居中对齐的。可以通过ParagraphgetJustification方法得到段落的对齐方式。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);

                     }

              }

       }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值