当前位置: 移动技术网 > IT编程>开发语言>Java > java Apache poi 对word doc文件进行读写操作

java Apache poi 对word doc文件进行读写操作

2019年07月22日  | 移动技术网IT编程  | 我要评论

大鸟阿力是谁,puma 故乡,yesewangchao

使用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所写)

 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网