读word doc文件2中方式
1.1 通过WordExtractor读文件(在WordExtractor内部进行信息读取时还是通过HWPFDocument来获取的。)
1.2 通过HWPFDocument读文件
Apache poi的hwpf模块是专门用来对word doc文件进行读写操作的。在hwpf里面我们使用HWPFDocument来表示一个word doc文档。在HWPFDocument里面有这么几个概念:
l Range:它表示一个范围,这个范围可以是整个文档,也可以是里面的某一小节(Section),也可以是某一个段落(Paragraph),还可以是拥有共同属性的一段文本(CharacterRun)。
l Section:word文档的一个小节,一个word文档可以由多个小节构成。
l Paragraph:word文档的一个段落,一个小节可以由多个段落构成。
l CharacterRun:具有相同属性的一段文本,一个段落可以由多个CharacterRun组成。
l Table:一个表格。
l TableRow:表格对应的行。
l TableCell:表格对应的单元格。
Section、Paragraph、CharacterRun和Table都继承自Range。
1.1 通过WordExtractor读文件
在使用WordExtractor读文件时我们只能读到文件的文本内容和基于文档的一些属性,至于文档内容的属性等是无法读到的。如果要读到文档内容的属性则需要使用HWPFDocument来读取了。下面是使用WordExtractor读取文件的一个示例:
- public class HwpfTest {
-
- @SuppressWarnings("deprecation")
- @Test
- public void testReadByExtractor() throws Exception {
- InputStream is = new FileInputStream("D:\\test.doc");
- WordExtractor extractor = new WordExtractor(is);
-
- System.out.println(extractor.getText());
- System.out.println(extractor.getTextFromPieces());
-
- System.out.println("页眉:" + extractor.getHeaderText());
-
- System.out.println("页脚:" + extractor.getFooterText());
-
- System.out.println(extractor.getMetadataTextExtractor().getText());
-
- String paraTexts[] = extractor.getParagraphText();
- for (int i=0; i<paraTexts.length; i++) {
- System.out.println("Paragraph " + (i+1) + " : " + paraTexts[i]);
- }
-
- printInfo(extractor.getSummaryInformation());
-
- this.printInfo(extractor.getDocSummaryInformation());
- this.closeStream(is);
- }
-
-
-
-
-
- private void printInfo(SummaryInformation info) {
-
- System.out.println(info.getAuthor());
-
- System.out.println(info.getCharCount());
-
- System.out.println(info.getPageCount());
-
- System.out.println(info.getTitle());
-
- System.out.println(info.getSubject());
- }
-
-
-
-
-
- private void printInfo(DocumentSummaryInformation info) {
-
- System.out.println(info.getCategory());
-
- System.out.println(info.getCompany());
- }
-
-
-
-
-
- private void closeStream(InputStream is) {
- if (is != null) {
- try {
- is.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- }
1.2 通过HWPFDocument读文件
HWPFDocument
是当前
Word
文档的代表,它的功能比
WordExtractor
要强。通过它我们可以读取文档中的表格、列表等,还可以对文档的内容进行新增、修改和删除操作。只是在进行完这些新增、修改和删除后相关信息是保存在
HWPFDocument
中的,也就是说我们改变的是
HWPFDocument
,而不是磁盘上的文件。如果要使这些修改生效的话,我们可以调用
HWPFDocument
的
write
方法把修改后的
HWPFDocument
输出到指定的输出流中。这可以是原文件的输出流,也可以是新文件的输出流(相当于另存为)或其它输出流。下面是一个通过
HWPFDocument
读文件的示例: