使用POI读写word docx文件

本文详细介绍了如何使用Java的POI库来读写docx文件,包括通过XWPFWordExtractor和XWPFDocument进行读取,以及直接创建和以模板为基础生成docx文件的方法。重点讲解了XWPFDocument中涉及的对象如XWPFParagraph、XWPFRun、XWPFTable等,并提供了示例代码。
摘要由CSDN通过智能技术生成

目录

1     docx文件

1.1     通过XWPFWordExtractor

1.2     通过XWPFDocument

2     docx文件

2.1     直接通过XWPFDocument生成

2.2     docx文件作为模板

 

       POI在读写word docx文件时是通过xwpf模块来进行的,其核心是XWPFDocument。一个XWPFDocument代表一个docx文档,其可以用来读docx文档,也可以用来写docx文档。XWPFDocument中主要包含下面这几种对象:

l  XWPFParagraph:代表一个段落。

l  XWPFRun:代表具有相同属性的一段文本。

l  XWPFTable:代表一个表格。

l  XWPFTableRow:表格的一行。

l  XWPFTableCell:表格对应的一个单元格。

 

1       读docx文件

       跟读doc文件一样,POI在读docx文件的时候也有两种方式,通过XWPFWordExtractor和通过XWPFDocument。在XWPFWordExtractor读取信息时其内部还是通过XWPFDocument来获取的。

1.1     通过XWPFWordExtractor读

       在使用XWPFWordExtractor读取docx文档的内容时,我们只能获取到其文本,而不能获取到其文本对应的属性值。下面是一段使用XWPFWordExtractor来读取docx文档内容的示例代码:

public class XwpfTest {
 
   /**
    * 通过XWPFWordExtractor访问XWPFDocument的内容
    * @throws Exception
    */
   @Test
   public void testReadByExtractor() throws Exception {
      InputStream is = new FileInputStream("D:\\test.docx");
      XWPFDocument doc = new XWPFDocument(is);
      XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
      String text = extractor.getText();
      System.out.println(text);
      CoreProperties coreProps = extractor.getCoreProperties();
      this.printCoreProperties(coreProps);
      this.close(is);
   }
  
   /**
    * 输出CorePrope
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值