Apache poi的hwpf模块是专门用来对word doc文件进行读写操作的。在hwpf里面我们使用HWPFDocument来表示一个word doc文档。在HWPFDocument里面有这么几个概念:

Range:它表示一个范围,这个范围可以是整个文档,也可以是里面的某一小节(Section),也可以是某一个段落(Paragraph),还可以是拥有共同属性的一段文本(CharacterRun)。

Section:word文档的一个小节,一个word文档可以由多个小节构成。

Paragraph:word文档的一个段落,一个小节可以由多个段落构成。

CharacterRun:具有相同属性的一段文本,一个段落可以由多个CharacterRun组成。

Table:一个表格。

TableRow:表格对应的行。

TableCell:表格对应的单元格。

Section、Paragraph、CharacterRun和Table都继承自Range。

1 读word doc文件

在日常应用中,我们从word文件里面读取信息的情况非常少见,更多的还是把内容写入到word文件中。使用POI从word doc文件读取数据时主要有两种方式:通过WordExtractor读和通过HWPFDocument读。在WordExtractor内部进行信息读取时还是通过HWPFDocument来获取的。

1.1通过WordExtractor读文件

在使用WordExtractor读文件时我们只能读到文件的文本内容和基于文档的一些属性,至于文档内容的属性等是无法读到的。如果要读到文档内容的属性则需要使用HWPFDocument来读取了。下面是使用WordExtractor读取文件的一个示例:

public class Test11 {
public static void main(String[] args) throws Exception {
InputStream is = new FileInputStream("F:\\test.doc");
WordExtractor extractor = new WordExtractor(is);
//输出word文档所有的文本
System.out.println(extractor.getText());
System.out.println(extractor.getTextFromPieces());
//输出页眉的内容
System.out.println("页眉:" + extractor.getHeaderText());
//输出页脚的内容
System.out.println("页脚:" + extractor.getFooterText());
//输出当前word文档的元数据信息,包括作者、文档的修改时间等。
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]);
}
//输出当前word的一些信息
printInfo(extractor.getSummaryInformation());
//输出当前word的一些信息
printInfo2(extractor.getDocSummaryInformation());
closeStream(is);
} /**
* 输出SummaryInfomation
* @param info
*/
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());
} /**
* 输出DocumentSummaryInfomation
* @param info
*/
private void printInfo2(DocumentSummaryInformation info) {
//分类
System.out.println(info.getCategory());
//公司
System.out.println(info.getCompany());
} /**
* 关闭输入流
* @param is
*/
private static 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读文件的示例:

public class HwpfTest {

   @Test
public void testReadByDoc() throws Exception {
InputStream is = new FileInputStream("D:\\test.doc");
HWPFDocument doc = new HWPFDocument(is);
//输出书签信息
this.printInfo(doc.getBookmarks());
//输出文本
System.out.println(doc.getDocumentText());
Range range = doc.getRange();
// this.insertInfo(range);
this.printInfo(range);
//读表格
this.readTable(range);
//读列表
this.readList(range);
//删除range
Range r = new Range(2, 5, doc);
r.delete();//在内存中进行删除,如果需要保存到文件中需要再把它写回文件
//把当前HWPFDocument写到输出流中
doc.write(new FileOutputStream("D:\\test.doc"));
this.closeStream(is);
} /**
* 关闭输入流
* @param is
*/
private void closeStream(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* 输出书签信息
* @param bookmarks
*/
private void printInfo(Bookmarks bookmarks) {
int count = bookmarks.getBookmarksCount();
System.out.println("书签数量:" + count);
Bookmark bookmark;
for (int i=0; i<count; i++) {
bookmark = bookmarks.getBookmark(i);
System.out.println("书签" + (i+1) + "的名称是:" + bookmark.getName());
System.out.println("开始位置:" + bookmark.getStart());
System.out.println("结束位置:" + bookmark.getEnd());
}
} /**
* 读表格
* 每一个回车符代表一个段落,所以对于表格而言,每一个单元格至少包含一个段落,每行结束都是一个段落。
* @param range
*/
private void readTable(Range range) {
//遍历range范围内的table。
TableIterator tableIter = new TableIterator(range);
Table table;
TableRow row;
TableCell cell;
while (tableIter.hasNext()) {
table = tableIter.next();
int rowNum = table.numRows();
for (int j=0; j<rowNum; j++) {
row = table.getRow(j);
int cellNum = row.numCells();
for (int k=0; k<cellNum; k++) {
cell = row.getCell(k);
//输出单元格的文本
System.out.println(cell.text().trim());
}
}
}
} /**
* 读列表
* @param range
*/
private void readList(Range range) {
int num = range.numParagraphs();
Paragraph para;
for (int i=0; i<num; i++) {
para = range.getParagraph(i);
if (para.isInList()) {
System.out.println("list: " + para.text());
}
}
} /**
* 输出Range
* @param range
*/
private void printInfo(Range range) {
//获取段落数
int paraNum = range.numParagraphs();
System.out.println(paraNum);
for (int i=0; i<paraNum; i++) {
// this.insertInfo(range.getParagraph(i));
System.out.println("段落" + (i+1) + ":" + range.getParagraph(i).text());
if (i == (paraNum-1)) {
this.insertInfo(range.getParagraph(i));
}
}
int secNum = range.numSections();
System.out.println(secNum);
Section section;
for (int i=0; i<secNum; i++) {
section = range.getSection(i);
System.out.println(section.getMarginLeft());
System.out.println(section.getMarginRight());
System.out.println(section.getMarginTop());
System.out.println(section.getMarginBottom());
System.out.println(section.getPageHeight());
System.out.println(section.text());
}
} /**
* 插入内容到Range,这里只会写到内存中
* @param range
*/
private void insertInfo(Range range) {
range.insertAfter("Hello");
} }

(注:本文是基于poi3.9所写)

POI读word doc 03 文件的两种方法的更多相关文章

  1. POI读word docx 07 文件的两种方法

    POI在读写word docx文件时是通过xwpf模块来进行的,其核心是XWPFDocument.一个XWPFDocument代表一个docx文档,其可以用来读docx文档,也可以用来写docx文档. ...

  2. [转载]C#读写txt文件的两种方法介绍

    C#读写txt文件的两种方法介绍 by 大龙哥 1.添加命名空间 System.IO; System.Text; 2.文件的读取 (1).使用FileStream类进行文件的读取,并将它转换成char ...

  3. .net中创建xml文件的两种方法

    .net中创建xml文件的两种方法 方法1:根据xml结构一步一步构建xml文档,保存文件(动态方式) 方法2:直接加载xml结构,保存文件(固定方式) 方法1:动态创建xml文档 根据传递的值,构建 ...

  4. MySQL命令执行sql文件的两种方法

    MySQL命令执行sql文件的两种方法 摘要:和其他数据库一样,MySQL也提供了命令执行sql脚本文件,方便地进行数据库.表以及数据等各种操作.下面笔者讲解MySQL执行sql文件命令的两种方法,希 ...

  5. C#读写txt文件的两种方法介绍

    C#读写txt文件的两种方法介绍 1.添加命名空间 System.IO; System.Text; 2.文件的读取 (1).使用FileStream类进行文件的读取,并将它转换成char数组,然后输出 ...

  6. spring 配置文件 引入外部的property文件的两种方法

    spring  的配置文件 引入外部的property文件的两种方法 <!-- 引入jdbc配置文件    方法一 --> <bean id="propertyConfig ...

  7. 合并BIN文件的两种方法(转)

    源:http://blog.chinaunix.net/uid-20745340-id-1878803.html 合并BIN文件的两种方法 在单片机的开发过程中,经常需要将两个单独的BIN文件合并成一 ...

  8. Linux下查看alert日志文件的两种方法

    --linux下查看alert日志文件的两种方法: --方法1: SQL> show parameter background_dump_dest; NAME TYPE VALUE ------ ...

  9. elf格式转换为hex格式文件的两种方法

    这周工作终于不太忙了,可以写点笔记总结一下了. 之前的文章如何在Keil-MDK开发环境生成Bin格式文件,介绍了如何在Keil开发环境使用fromelf软件,将生成的axf文件转换为bin文件,这次 ...

随机推荐

  1. HDU4973 【几何。】

    题意: 给你一个以原点为圆心的两个圆,一个大圆,一个小圆,然后给你一个硬币和他的速度,问你经过大圆的时间: 思路: 直接杠.. 然后wa的怀疑人生,后面wa在了速度的方向,如果我说一个点在两个圆的左上 ...

  2. HDU 1556【线段树区间更新】

    这篇lazy讲的很棒: https://www.douban.com/note/273509745/ if(tree[rt].l == l && r == tree[rt].r) 这里 ...

  3. [HNOI2010] 合唱队 chorus

    标签:区间DP.题解: 首先分析题目,根据题目中的列队方式以及数据范围,我们容易想到O(n2)的算法,也就是区间DP.发现直接dp[L][R],不能转移,于是添加一个dp[L][R][0/1],0表示 ...

  4. [Xcode 实际操作]一、博主领进门-(3)使用资源文件夹(Assets.xcassets)导入并管理图片素材

    目录:[Swift]Xcode实际操作 本文将演示如何使用资源文件夹(Assets.xcassets)导入并管理图片素材. [Assets.xcassets]资源文件夹可以方便的进行图片的管理, 在读 ...

  5. OFFICE 365 A1 Plus账号注册

    OFFICE365 A1 Plus账号注册 Office2019与Office365专业增强版之间的区别: Office2019是一次性购买,不会在购买后接收功能更新,但会根据需要接收质量和安全修补程 ...

  6. IP服务-3-DHCP

    DHCP代表了动态IP地址分配的下一阶段.DHCP建立在BOOTP协议格式的基础上,专注于动态分配多种信息,以及为未来的扩展提供灵活的消息结构,并且无需预先定义每个客户端的MAC地址.DHCP提供的功 ...

  7. IP服务-1-ARP和代理ARP

    代理ARP常被人忽视,因为现在基本不用了

  8. python之yagmail发送邮件

    yagmail发送邮件 import yagmail yag = yagmail.SMTP(user="xxxxxxxxxx@163.com",password="xxx ...

  9. bzoj4059 [Cerc2012]Non-boring sequences && bzoj5200 [NWERC2017]Factor-Free Tree

    https://konnyakuxzy.github.io/BZPRO/JudgeOnline/4059.html https://cn.vjudge.net/problem/Gym-100624D ...

  10. [转] boost:lexical_cast用法

    转载地址:http://www.habadog.com/2011/05/07/boost-lexical_cast-intro/ 一.lexical_cast的作用lexical_cast使用统一的接 ...