目录
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