目录

1     读word doc文件

1.1     通过WordExtractor读文件

1.2     通过HWPFDocument读文件

2     写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读取文件的一个示例:

  1. public class HwpfTest {
  2. @SuppressWarnings("deprecation")
  3. @Test
  4. public void testReadByExtractor() throws Exception {
  5. InputStream is = new FileInputStream("D:\\test.doc");
  6. WordExtractor extractor = new WordExtractor(is);
  7. //输出word文档所有的文本
  8. System.out.println(extractor.getText());
  9. System.out.println(extractor.getTextFromPieces());
  10. //输出页眉的内容
  11. System.out.println("页眉:" + extractor.getHeaderText());
  12. //输出页脚的内容
  13. System.out.println("页脚:" + extractor.getFooterText());
  14. //输出当前word文档的元数据信息,包括作者、文档的修改时间等。
  15. System.out.println(extractor.getMetadataTextExtractor().getText());
  16. //获取各个段落的文本
  17. String paraTexts[] = extractor.getParagraphText();
  18. for (int i=0; i<paraTexts.length; i++) {
  19. System.out.println("Paragraph " + (i+1) + " : " + paraTexts[i]);
  20. }
  21. //输出当前word的一些信息
  22. printInfo(extractor.getSummaryInformation());
  23. //输出当前word的一些信息
  24. this.printInfo(extractor.getDocSummaryInformation());
  25. this.closeStream(is);
  26. }
  27. /**
  28. * 输出SummaryInfomation
  29. * @param info
  30. */
  31. private void printInfo(SummaryInformation info) {
  32. //作者
  33. System.out.println(info.getAuthor());
  34. //字符统计
  35. System.out.println(info.getCharCount());
  36. //页数
  37. System.out.println(info.getPageCount());
  38. //标题
  39. System.out.println(info.getTitle());
  40. //主题
  41. System.out.println(info.getSubject());
  42. }
  43. /**
  44. * 输出DocumentSummaryInfomation
  45. * @param info
  46. */
  47. private void printInfo(DocumentSummaryInformation info) {
  48. //分类
  49. System.out.println(info.getCategory());
  50. //公司
  51. System.out.println(info.getCompany());
  52. }
  53. /**
  54. * 关闭输入流
  55. * @param is
  56. */
  57. private void closeStream(InputStream is) {
  58. if (is != null) {
  59. try {
  60. is.close();
  61. } catch (IOException e) {
  62. e.printStackTrace();
  63. }
  64. }
  65. }
  66. }
  1. public class HwpfTest {
  2.  
  3. @SuppressWarnings("deprecation")
  4. @Test
  5. public void testReadByExtractor() throws Exception {
  6. InputStream is = new FileInputStream("D:\\test.doc");
  7. WordExtractor extractor = new WordExtractor(is);
  8. //输出word文档所有的文本
  9. System.out.println(extractor.getText());
  10. System.out.println(extractor.getTextFromPieces());
  11. //输出页眉的内容
  12. System.out.println("页眉:" + extractor.getHeaderText());
  13. //输出页脚的内容
  14. System.out.println("页脚:" + extractor.getFooterText());
  15. //输出当前word文档的元数据信息,包括作者、文档的修改时间等。
  16. System.out.println(extractor.getMetadataTextExtractor().getText());
  17. //获取各个段落的文本
  18. String paraTexts[] = extractor.getParagraphText();
  19. for (int i=0; i<paraTexts.length; i++) {
  20. System.out.println("Paragraph " + (i+1) + " : " + paraTexts[i]);
  21. }
  22. //输出当前word的一些信息
  23. printInfo(extractor.getSummaryInformation());
  24. //输出当前word的一些信息
  25. this.printInfo(extractor.getDocSummaryInformation());
  26. this.closeStream(is);
  27. }
  28.  
  29. /**
  30. * 输出SummaryInfomation
  31. * @param info
  32. */
  33. private void printInfo(SummaryInformation info) {
  34. //作者
  35. System.out.println(info.getAuthor());
  36. //字符统计
  37. System.out.println(info.getCharCount());
  38. //页数
  39. System.out.println(info.getPageCount());
  40. //标题
  41. System.out.println(info.getTitle());
  42. //主题
  43. System.out.println(info.getSubject());
  44. }
  45.  
  46. /**
  47. * 输出DocumentSummaryInfomation
  48. * @param info
  49. */
  50. private void printInfo(DocumentSummaryInformation info) {
  51. //分类
  52. System.out.println(info.getCategory());
  53. //公司
  54. System.out.println(info.getCompany());
  55. }
  56.  
  57. /**
  58. * 关闭输入流
  59. * @param is
  60. */
  61. private void closeStream(InputStream is) {
  62. if (is != null) {
  63. try {
  64. is.close();
  65. } catch (IOException e) {
  66. e.printStackTrace();
  67. }
  68. }
  69. }
  70.  
  71. }

1.2     通过HWPFDocument读文件

HWPFDocument是当前Word文档的代表,它的功能比WordExtractor要强。通过它我们可以读取文档中的表格、列表等,还可以对文档的内容进行新增、修改和删除操作。只是在进行完这些新增、修改和删除后相关信息是保存在HWPFDocument中的,也就是说我们改变的是HWPFDocument,而不是磁盘上的文件。如果要使这些修改生效的话,我们可以调用HWPFDocument的write方法把修改后的HWPFDocument输出到指定的输出流中。这可以是原文件的输出流,也可以是新文件的输出流(相当于另存为)或其它输出流。下面是一个通过HWPFDocument读文件的示例:

  1. public class HwpfTest {
  2. @Test
  3. public void testReadByDoc() throws Exception {
  4. InputStream is = new FileInputStream("D:\\test.doc");
  5. HWPFDocument doc = new HWPFDocument(is);
  6. //输出书签信息
  7. this.printInfo(doc.getBookmarks());
  8. //输出文本
  9. System.out.println(doc.getDocumentText());
  10. Range range = doc.getRange();
  11. //    this.insertInfo(range);
  12. this.printInfo(range);
  13. //读表格
  14. this.readTable(range);
  15. //读列表
  16. this.readList(range);
  17. //删除range
  18. Range r = new Range(2, 5, doc);
  19. r.delete();//在内存中进行删除,如果需要保存到文件中需要再把它写回文件
  20. //把当前HWPFDocument写到输出流中
  21. doc.write(new FileOutputStream("D:\\test.doc"));
  22. this.closeStream(is);
  23. }
  24. /**
  25. * 关闭输入流
  26. * @param is
  27. */
  28. private void closeStream(InputStream is) {
  29. if (is != null) {
  30. try {
  31. is.close();
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. }
  37. /**
  38. * 输出书签信息
  39. * @param bookmarks
  40. */
  41. private void printInfo(Bookmarks bookmarks) {
  42. int count = bookmarks.getBookmarksCount();
  43. System.out.println("书签数量:" + count);
  44. Bookmark bookmark;
  45. for (int i=0; i<count; i++) {
  46. bookmark = bookmarks.getBookmark(i);
  47. System.out.println("书签" + (i+1) + "的名称是:" + bookmark.getName());
  48. System.out.println("开始位置:" + bookmark.getStart());
  49. System.out.println("结束位置:" + bookmark.getEnd());
  50. }
  51. }
  52. /**
  53. * 读表格
  54. * 每一个回车符代表一个段落,所以对于表格而言,每一个单元格至少包含一个段落,每行结束都是一个段落。
  55. * @param range
  56. */
  57. private void readTable(Range range) {
  58. //遍历range范围内的table。
  59. TableIterator tableIter = new TableIterator(range);
  60. Table table;
  61. TableRow row;
  62. TableCell cell;
  63. while (tableIter.hasNext()) {
  64. table = tableIter.next();
  65. int rowNum = table.numRows();
  66. for (int j=0; j<rowNum; j++) {
  67. row = table.getRow(j);
  68. int cellNum = row.numCells();
  69. for (int k=0; k<cellNum; k++) {
  70. cell = row.getCell(k);
  71. //输出单元格的文本
  72. System.out.println(cell.text().trim());
  73. }
  74. }
  75. }
  76. }
  77. /**
  78. * 读列表
  79. * @param range
  80. */
  81. private void readList(Range range) {
  82. int num = range.numParagraphs();
  83. Paragraph para;
  84. for (int i=0; i<num; i++) {
  85. para = range.getParagraph(i);
  86. if (para.isInList()) {
  87. System.out.println("list: " + para.text());
  88. }
  89. }
  90. }
  91. /**
  92. * 输出Range
  93. * @param range
  94. */
  95. private void printInfo(Range range) {
  96. //获取段落数
  97. int paraNum = range.numParagraphs();
  98. System.out.println(paraNum);
  99. for (int i=0; i<paraNum; i++) {
  100. //       this.insertInfo(range.getParagraph(i));
  101. System.out.println("段落" + (i+1) + ":" + range.getParagraph(i).text());
  102. if (i == (paraNum-1)) {
  103. this.insertInfo(range.getParagraph(i));
  104. }
  105. }
  106. int secNum = range.numSections();
  107. System.out.println(secNum);
  108. Section section;
  109. for (int i=0; i<secNum; i++) {
  110. section = range.getSection(i);
  111. System.out.println(section.getMarginLeft());
  112. System.out.println(section.getMarginRight());
  113. System.out.println(section.getMarginTop());
  114. System.out.println(section.getMarginBottom());
  115. System.out.println(section.getPageHeight());
  116. System.out.println(section.text());
  117. }
  118. }
  119. /**
  120. * 插入内容到Range,这里只会写到内存中
  121. * @param range
  122. */
  123. private void insertInfo(Range range) {
  124. range.insertAfter("Hello");
  125. }
  126. }
  1. public class HwpfTest {
  2.  
  3. @Test
  4. public void testReadByDoc() throws Exception {
  5. InputStream is = new FileInputStream("D:\\test.doc");
  6. HWPFDocument doc = new HWPFDocument(is);
  7. //输出书签信息
  8. this.printInfo(doc.getBookmarks());
  9. //输出文本
  10. System.out.println(doc.getDocumentText());
  11. Range range = doc.getRange();
  12. // this.insertInfo(range);
  13. this.printInfo(range);
  14. //读表格
  15. this.readTable(range);
  16. //读列表
  17. this.readList(range);
  18. //删除range
  19. Range r = new Range(2, 5, doc);
  20. r.delete();//在内存中进行删除,如果需要保存到文件中需要再把它写回文件
  21. //把当前HWPFDocument写到输出流中
  22. doc.write(new FileOutputStream("D:\\test.doc"));
  23. this.closeStream(is);
  24. }
  25.  
  26. /**
  27. * 关闭输入流
  28. * @param is
  29. */
  30. private void closeStream(InputStream is) {
  31. if (is != null) {
  32. try {
  33. is.close();
  34. } catch (IOException e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. }
  39.  
  40. /**
  41. * 输出书签信息
  42. * @param bookmarks
  43. */
  44. private void printInfo(Bookmarks bookmarks) {
  45. int count = bookmarks.getBookmarksCount();
  46. System.out.println("书签数量:" + count);
  47. Bookmark bookmark;
  48. for (int i=0; i<count; i++) {
  49. bookmark = bookmarks.getBookmark(i);
  50. System.out.println("书签" + (i+1) + "的名称是:" + bookmark.getName());
  51. System.out.println("开始位置:" + bookmark.getStart());
  52. System.out.println("结束位置:" + bookmark.getEnd());
  53. }
  54. }
  55.  
  56. /**
  57. * 读表格
  58. * 每一个回车符代表一个段落,所以对于表格而言,每一个单元格至少包含一个段落,每行结束都是一个段落。
  59. * @param range
  60. */
  61. private void readTable(Range range) {
  62. //遍历range范围内的table。
  63. TableIterator tableIter = new TableIterator(range);
  64. Table table;
  65. TableRow row;
  66. TableCell cell;
  67. while (tableIter.hasNext()) {
  68. table = tableIter.next();
  69. int rowNum = table.numRows();
  70. for (int j=0; j<rowNum; j++) {
  71. row = table.getRow(j);
  72. int cellNum = row.numCells();
  73. for (int k=0; k<cellNum; k++) {
  74. cell = row.getCell(k);
  75. //输出单元格的文本
  76. System.out.println(cell.text().trim());
  77. }
  78. }
  79. }
  80. }
  81.  
  82. /**
  83. * 读列表
  84. * @param range
  85. */
  86. private void readList(Range range) {
  87. int num = range.numParagraphs();
  88. Paragraph para;
  89. for (int i=0; i<num; i++) {
  90. para = range.getParagraph(i);
  91. if (para.isInList()) {
  92. System.out.println("list: " + para.text());
  93. }
  94. }
  95. }
  96.  
  97. /**
  98. * 输出Range
  99. * @param range
  100. */
  101. private void printInfo(Range range) {
  102. //获取段落数
  103. int paraNum = range.numParagraphs();
  104. System.out.println(paraNum);
  105. for (int i=0; i<paraNum; i++) {
  106. // this.insertInfo(range.getParagraph(i));
  107. System.out.println("段落" + (i+1) + ":" + range.getParagraph(i).text());
  108. if (i == (paraNum-1)) {
  109. this.insertInfo(range.getParagraph(i));
  110. }
  111. }
  112. int secNum = range.numSections();
  113. System.out.println(secNum);
  114. Section section;
  115. for (int i=0; i<secNum; i++) {
  116. section = range.getSection(i);
  117. System.out.println(section.getMarginLeft());
  118. System.out.println(section.getMarginRight());
  119. System.out.println(section.getMarginTop());
  120. System.out.println(section.getMarginBottom());
  121. System.out.println(section.getPageHeight());
  122. System.out.println(section.text());
  123. }
  124. }
  125.  
  126. /**
  127. * 插入内容到Range,这里只会写到内存中
  128. * @param range
  129. */
  130. private void insertInfo(Range range) {
  131. range.insertAfter("Hello");
  132. }
  133.  
  134. }

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输出到对应的输出流即可。下面是对应的代码。

  1. public class HwpfTest {
  2. @Test
  3. public void testWrite() throws Exception {
  4. String templatePath = "D:\\word\\template.doc";
  5. InputStream is = new FileInputStream(templatePath);
  6. HWPFDocument doc = new HWPFDocument(is);
  7. Range range = doc.getRange();
  8. //把range范围内的${reportDate}替换为当前的日期
  9. range.replaceText("${reportDate}", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
  10. range.replaceText("${appleAmt}", "100.00");
  11. range.replaceText("${bananaAmt}", "200.00");
  12. range.replaceText("${totalAmt}", "300.00");
  13. OutputStream os = new FileOutputStream("D:\\word\\write.doc");
  14. //把doc输出到输出流中
  15. doc.write(os);
  16. this.closeStream(os);
  17. this.closeStream(is);
  18. }
  19. /**
  20. * 关闭输入流
  21. * @param is
  22. */
  23. private void closeStream(InputStream is) {
  24. if (is != null) {
  25. try {
  26. is.close();
  27. } catch (IOException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. }
  32. /**
  33. * 关闭输出流
  34. * @param os
  35. */
  36. private void closeStream(OutputStream os) {
  37. if (os != null) {
  38. try {
  39. os.close();
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. }
  45. }
  1. public class HwpfTest {
  2.  
  3. @Test
  4. public void testWrite() throws Exception {
  5. String templatePath = "D:\\word\\template.doc";
  6. InputStream is = new FileInputStream(templatePath);
  7. HWPFDocument doc = new HWPFDocument(is);
  8. Range range = doc.getRange();
  9. //把range范围内的${reportDate}替换为当前的日期
  10. range.replaceText("${reportDate}", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
  11. range.replaceText("${appleAmt}", "100.00");
  12. range.replaceText("${bananaAmt}", "200.00");
  13. range.replaceText("${totalAmt}", "300.00");
  14. OutputStream os = new FileOutputStream("D:\\word\\write.doc");
  15. //把doc输出到输出流中
  16. doc.write(os);
  17. this.closeStream(os);
  18. this.closeStream(is);
  19. }
  20.  
  21. /**
  22. * 关闭输入流
  23. * @param is
  24. */
  25. private void closeStream(InputStream is) {
  26. if (is != null) {
  27. try {
  28. is.close();
  29. } catch (IOException e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. }
  34.  
  35. /**
  36. * 关闭输出流
  37. * @param os
  38. */
  39. private void closeStream(OutputStream os) {
  40. if (os != null) {
  41. try {
  42. os.close();
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. }
  46. }
  47. }
  48.  
  49. }

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

android使用POI读写word doc文件的更多相关文章

  1. 使用POI读写Word doc文件

    使用POI读写word doc文件 目录 1     读word doc文件 1.1     通过WordExtractor读文件 1.2     通过HWPFDocument读文件 2     写w ...

  2. POI读写Word docx文件

    使用POI读写word docx文件 目录 1     读docx文件 1.1     通过XWPFWordExtractor读 1.2     通过XWPFDocument读 2     写docx ...

  3. 使用POI读写word docx文件

    目录 1     读docx文件 1.1     通过XWPFWordExtractor读 1.2     通过XWPFDocument读 2     写docx文件 2.1     直接通过XWPF ...

  4. 使用POI转换word doc文件

    目录 1       转换为Html文件 2       转换为Xml文件 3       转换为Text文件 在POI中还存在有针对于word doc文件进行格式转换的功能.我们可以将word的内容 ...

  5. POI转换word doc文件为(html,xml,txt)

    在POI中还存在有针对于word doc文件进行格式转换的功能.我们可以将word的内容转换为对应的Html文件,也可以把它转换为底层用来描述doc文档的xml文件,还可以把它转换为底层用来描述doc ...

  6. POI读word doc 03 文件的两种方法

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

  7. POI写入word doc 03 模板的实例

    在使用POI写word doc文件的时候我们必须要先有一个doc文件才行,因为我们在写doc文件的时候是通过HWPFDocument来写的,而HWPFDocument是要依附于一个doc文件的.所以通 ...

  8. VBA/VBScript提取Word(*.doc)文件中包含的图片(照片)

    VBA/VBScript提取Word(*.doc)文件中包含的图片(照片)   要处理的人事简历表是典型的Word文档,其中一人一份doc,里面包含有个人的照片,如果要把里面的照片复制出来就比较麻烦了 ...

  9. POI把html写入word doc文件

    直接把Html文本写入到Word文件 获取查看页面的body内容和引用的css文件路径传入到后台. 把对应css文件的内容读取出来. 利用body内容和css文件的内容组成一个标准格式的Html文本. ...

随机推荐

  1. Linux中svn的使用

    1. 安装Linux 执行如下命令,中间会出现一次提示,选y即可 yum install subversion 2. 创建资源库位置 svnadmin create /usr/java/testJen ...

  2. svn备份与还原_脚本_(dump命令)

    今天备份svn, 能保证好用就行先, 回头再研究 buerguo.bat @echo off :: 关闭回显 :: 说明:如有命令不明白,请使用帮助命令:命令/? .如:for/? :: 设置标题 t ...

  3. 使用T-SQL语句操作视图

    转自:使用T-SQL语句操作视图 提示:只能查看,删除,创建视图,不能对数据进行增,删,改操作. use StuManageDB go --判断视图是否存在 if exists(Select * fr ...

  4. ubuntu安装包查找及安装

    官方包源: http://packages.ubuntu.com/ ubuntu下当前安装的包保存在在:/var/cache/apt/archives ubuntu下当前安装的运用: /usr/sha ...

  5. 使用 WM_COPYDATA 在进程间共享数据

    开发中有时需要进程间传递数据,比如对于只允许单实例运行的程序,当已有实例运行时,再次打开程序,可能需要向当前运行的实例传递信息进行特殊处理.对于传递少量数据的情况,最简单的就是用SendMessage ...

  6. 《JAVA与模式》之访问者模式

    在阎宏博士的<JAVA与模式>一书中开头是这样描述访问者(Visitor)模式的: 访问者模式是对象的行为模式.访问者模式的目的是封装一些施加于某种数据结构元素之上的操作.一旦这些操作需要 ...

  7. Could not connect to Redis at xxx.xxx.xxx.xxx:6379: Connection refused

    开发发来消息说测试环境的redis无法登录: # redis-cli -p 6379 -h xxx.xxx.xxx.xxx Could not connect to Redis at xxx.xxx. ...

  8. Android之内存泄露、内存溢出、内存抖动分析

      内存   JAVA是在JVM所虚拟出的内存环境中运行的,内存分为三个区:堆.栈和方法区.栈(stack):是简单的数据结构,程序运行时系统自动分配,使用完毕后自动释放.优点:速度快.堆(heap) ...

  9. 你应该学会使用的5个ruby方法

    今天看到了这篇文章--Five Ruby Methods You Should Be Using,感觉收获颇丰,先简单翻译一下先. 作者写这篇文章的契机是在Exercism上看到了很多ruby代码可以 ...

  10. htmlentities、addslashes 、htmlspecialchars的使用

    1.html_entity_decode():把html实体转换为字符. Eg:$str = "just atest & 'learn to use '";echo htm ...