这里有新鲜出炉的 Java 并发编程示例,程序狗速度看过来!
java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的 Java 程序设计语言和 Java 平台(即 JavaEE(j2ee), JavaME(j2me), JavaSE(j2se))的总称。
这篇文章主要介绍了 Apache poi 对 word doc 文件进行读写操作的相关资料, 需要的朋友可以参考下
使用 POI 读写 Word doc 文件
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 HwpfTest {
- @SuppressWarnings("deprecation")@Test public void testReadByExtractor() throws Exception {
- InputStream is = new FileInputStream("D:\\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的一些信息
- this.printInfo(extractor.getDocSummaryInformation());
- this.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 printInfo(DocumentSummaryInformation info) {
- //分类
- System.out.println(info.getCategory());
- //公司
- System.out.println(info.getCompany());
- }
- /**
- * 关闭输入流
- * @param is
- */
- 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 读文件的示例:
- 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");
- }
- }
2 写 word doc 文件
在使用 POI 写 word doc 文件的时候我们必须要先有一个 doc 文件才行,因为我们在写 doc 文件的时候是通过 HWPFDocument 来写的,而 HWPFDocument 是要依附于一个 doc 文件的。所以通常的做法是我们先在硬盘上准备好一个内容空白的 doc 文件,然后建立一个基于该空白文件的 HWPFDocument。之后我们就可以往 HWPFDocument 里面新增内容了,然后再把它写入到另外一个 doc 文件中,这样就相当于我们使用 POI 生成了 word doc 文件。
在实际应用中,我们在生成 word 文件的时候都是生成某一类文件,该类文件的格式是固定的,只是某些字段不一样罢了。所以在实际应用中,我们大可不必将整个 word 文件的内容都通过 HWPFDocument 生成。而是先在磁盘上新建一个 word 文档,其内容就是我们需要生成的 word 文件的内容,然后把里面一些属于变量的内容使用类似于 "${paramName}" 这样的方式代替。这样我们在基于某些信息生成 word 文件的时候,只需要获取基于该 word 文件的 HWPFDocument,然后调用 Range 的 replaceText() 方法把对应的变量替换为对应的值即可,之后再把当前的 HWPFDocument 写入到新的输出流中。这种方式在实际应用中用的比较多,因为它不但可以减少我们的工作量,还可以让文本的格式更加的清晰。下面我们就来基于这种方式做一个示例。
假设我们现在拥有一些变动的信息,然后需要通过这些信息生成如下格式的 word doc 文件:
那么根据上面的描述,首先第一步,我们建立一个对应格式的 doc 文件作为模板,其内容是这样的:
有了这样一个模板之后,我们就可以建立对应的 HWPFDocument,然后替换对应的变量为相应的值,再把 HWPFDocument 输出到对应的输出流即可。下面是对应的代码。
- public class HwpfTest {
- @Test public void testWrite() throws Exception {
- String templatePath = "D:\\word\\template.doc";
- InputStream is = new FileInputStream(templatePath);
- HWPFDocument doc = new HWPFDocument(is);
- Range range = doc.getRange();
- //把range范围内的${reportDate}替换为当前的日期
- range.replaceText("${reportDate}", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
- range.replaceText("${appleAmt}", "100.00");
- range.replaceText("${bananaAmt}", "200.00");
- range.replaceText("${totalAmt}", "300.00");
- OutputStream os = new FileOutputStream("D:\\word\\write.doc");
- //把doc输出到输出流中
- doc.write(os);
- this.closeStream(os);
- this.closeStream(is);
- }
- /**
- * 关闭输入流
- * @param is
- */
- private void closeStream(InputStream is) {
- if (is != null) {
- try {
- is.close();
- } catch(IOException e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * 关闭输出流
- * @param os
- */
- private void closeStream(OutputStream os) {
- if (os != null) {
- try {
- os.close();
- } catch(IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
(注:本文是基于 poi3.9 所写)
来源: http://www.phperz.com/article/17/1215/358977.html