android使用POI读写word doc文件

摘要:
目录1读worddoc文件1.1通过WordExtractor读文件1.2通过HWPFDocument读文件2写worddoc文件Apachepoi的hwpf模块是专门用来对worddoc文件进行读写操作的。在hwpf里面我们使用HWPFDocument来表示一个worddoc文档。lSection:word文档的一个小节,一个word文档可以由多个小节构成。1读worddoc文件在日常应用中,我们从word文件里面读取信息的情况非常少见,更多的还是把内容写入到word文件中。使用POI从worddoc文件读取数据时主要有两种方式:通过WordExtractor读和通过HWPFDocument读。

目录

1 读word doc文件

1.1 通过WordExtractor读文件

1.2 通过HWPFDocument读文件

2 写word doc文件

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 读word doc文件

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

1.1 通过WordExtractor读文件

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

Java代码
  1. publicclassHwpfTest{
  2. @SuppressWarnings("deprecation")
  3. @Test
  4. publicvoidtestReadByExtractor()throwsException{
  5. InputStreamis=newFileInputStream("D:\test.doc");
  6. WordExtractorextractor=newWordExtractor(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. StringparaTexts[]=extractor.getParagraphText();
  18. for(inti=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. *@paraminfo
  30. */
  31. privatevoidprintInfo(SummaryInformationinfo){
  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. *@paraminfo
  46. */
  47. privatevoidprintInfo(DocumentSummaryInformationinfo){
  48. //分类
  49. System.out.println(info.getCategory());
  50. //公司
  51. System.out.println(info.getCompany());
  52. }
  53. /**
  54. *关闭输入流
  55. *@paramis
  56. */
  57. privatevoidcloseStream(InputStreamis){
  58. if(is!=null){
  59. try{
  60. is.close();
  61. }catch(IOExceptione){
  62. e.printStackTrace();
  63. }
  64. }
  65. }
  66. }
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读文件的示例:

Java代码
  1. publicclassHwpfTest{
  2. @Test
  3. publicvoidtestReadByDoc()throwsException{
  4. InputStreamis=newFileInputStream("D:\test.doc");
  5. HWPFDocumentdoc=newHWPFDocument(is);
  6. //输出书签信息
  7. this.printInfo(doc.getBookmarks());
  8. //输出文本
  9. System.out.println(doc.getDocumentText());
  10. Rangerange=doc.getRange();
  11. //this.insertInfo(range);
  12. this.printInfo(range);
  13. //读表格
  14. this.readTable(range);
  15. //读列表
  16. this.readList(range);
  17. //删除range
  18. Ranger=newRange(2,5,doc);
  19. r.delete();//在内存中进行删除,如果需要保存到文件中需要再把它写回文件
  20. //把当前HWPFDocument写到输出流中
  21. doc.write(newFileOutputStream("D:\test.doc"));
  22. this.closeStream(is);
  23. }
  24. /**
  25. *关闭输入流
  26. *@paramis
  27. */
  28. privatevoidcloseStream(InputStreamis){
  29. if(is!=null){
  30. try{
  31. is.close();
  32. }catch(IOExceptione){
  33. e.printStackTrace();
  34. }
  35. }
  36. }
  37. /**
  38. *输出书签信息
  39. *@parambookmarks
  40. */
  41. privatevoidprintInfo(Bookmarksbookmarks){
  42. intcount=bookmarks.getBookmarksCount();
  43. System.out.println("书签数量:"+count);
  44. Bookmarkbookmark;
  45. for(inti=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. *@paramrange
  56. */
  57. privatevoidreadTable(Rangerange){
  58. //遍历range范围内的table。
  59. TableIteratortableIter=newTableIterator(range);
  60. Tabletable;
  61. TableRowrow;
  62. TableCellcell;
  63. while(tableIter.hasNext()){
  64. table=tableIter.next();
  65. introwNum=table.numRows();
  66. for(intj=0;j<rowNum;j++){
  67. row=table.getRow(j);
  68. intcellNum=row.numCells();
  69. for(intk=0;k<cellNum;k++){
  70. cell=row.getCell(k);
  71. //输出单元格的文本
  72. System.out.println(cell.text().trim());
  73. }
  74. }
  75. }
  76. }
  77. /**
  78. *读列表
  79. *@paramrange
  80. */
  81. privatevoidreadList(Rangerange){
  82. intnum=range.numParagraphs();
  83. Paragraphpara;
  84. for(inti=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. *@paramrange
  94. */
  95. privatevoidprintInfo(Rangerange){
  96. //获取段落数
  97. intparaNum=range.numParagraphs();
  98. System.out.println(paraNum);
  99. for(inti=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. intsecNum=range.numSections();
  107. System.out.println(secNum);
  108. Sectionsection;
  109. for(inti=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. *@paramrange
  122. */
  123. privatevoidinsertInfo(Rangerange){
  124. range.insertAfter("Hello");
  125. }
  126. }
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输出到对应的输出流即可。下面是对应的代码。

Java代码
  1. publicclassHwpfTest{
  2. @Test
  3. publicvoidtestWrite()throwsException{
  4. StringtemplatePath="D:\word\template.doc";
  5. InputStreamis=newFileInputStream(templatePath);
  6. HWPFDocumentdoc=newHWPFDocument(is);
  7. Rangerange=doc.getRange();
  8. //把range范围内的${reportDate}替换为当前的日期
  9. range.replaceText("${reportDate}",newSimpleDateFormat("yyyy-MM-dd").format(newDate()));
  10. range.replaceText("${appleAmt}","100.00");
  11. range.replaceText("${bananaAmt}","200.00");
  12. range.replaceText("${totalAmt}","300.00");
  13. OutputStreamos=newFileOutputStream("D:\word\write.doc");
  14. //把doc输出到输出流中
  15. doc.write(os);
  16. this.closeStream(os);
  17. this.closeStream(is);
  18. }
  19. /**
  20. *关闭输入流
  21. *@paramis
  22. */
  23. privatevoidcloseStream(InputStreamis){
  24. if(is!=null){
  25. try{
  26. is.close();
  27. }catch(IOExceptione){
  28. e.printStackTrace();
  29. }
  30. }
  31. }
  32. /**
  33. *关闭输出流
  34. *@paramos
  35. */
  36. privatevoidcloseStream(OutputStreamos){
  37. if(os!=null){
  38. try{
  39. os.close();
  40. }catch(IOExceptione){
  41. e.printStackTrace();
  42. }
  43. }
  44. }
  45. }
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所写)

免责声明:文章转载自《android使用POI读写word doc文件》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇vue 图片上传功能嵌入式Linux学习笔记(四) 设备树和UART驱动开发下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

用 c# 来操作WORD的经验总结

最近在做一个程序,需要在程序中对Word内容做些处理。从网上查了很多资料,发现,许多都是重复的。更有许多知识,根本没有讲到。为了以后使用方便。将所有的这些知识,加以总结,以备后来人使用。 1、引用     需要引用 COM库:Microsoft word 11.0 Object Library. 不同的版本,会有不同的版本号。    如 2010版Offi...

双层PDF的制作——使用PDF4NET 3.3.6 实现

双层PDF的制作——使用PDF4NET 3.3.6 实现 所谓双层PDF就是每一页都包含两层,上层是图像,下层是该图像对应的文字。既可以像图像一样浏览,又可以像文字一样复制、查找。这样兼顾了阅读的效果和使用方便性。 在Google里面搜索,大多数双层PDF制作方法都是使用OCR技术实现的。这些方法的制作前提是,原始的数据只是图片,不存在对应的文字版。这...

使用curses管理基于文本的屏幕--(八)

CD管理程序现在我们已经了解了curses所提供了功能,我们可以继续开发我们的例子程序。在这里所展示是一个使用curses库的C语言版本。他提供了一些高级的特性,包括更为清晰的屏幕信息显示以及用于跟踪列表的滚动窗口。完整的程序共页长,所以我们将其分为几部分,在每一部分中介绍一些函数。试验--一个新的CD管理程序1 首先,我们包含所有的头文件以及一些全局常量...

NPOI 2.0导出word(docx格式)

大名鼎鼎的NPOI用来导出EXCEL的文章园子里面有很多,可是用来导出WORD文档的文章大都含糊不清,最近刚好完成一个导出WORD文档的需求,在此分享下。 NPOI里面认为word文档的最基本的结构是段落,代表这个段落的类就是XWPFParagraph,使用这个类可以设置段落里面的字体、大小、以及是否加粗等。 代表整个文档的的类XWPFDocument,是...

如何用Apache POI操作Excel文件-----如何对一个单元格加注解?

有的时候,我们需要通过操作Apache POI,在生成Cell数据的同时,能对其生成的Cell,加上注解(comments),类似于下面的。 那么对于这种情况,我们的代码应该如何写呢? 借花献佛,我就用Apache POI官方提供的例子,然后加上一些注解,给大家看一下。本例子的测试代码是基于POI-3.12的。 执行完后,将会生成上图所示的Excel工作...

【JAVA】POI生成EXCEL图表(柱状图、折线等)

1、使用excel工具自带的图形工具创建一个图: 2、绑定数据区域: 3、数据区域绑定完成,我们要做的就是将数据写入到数据区域中: 4、标记 5、POI 引入包 <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency>...