XWPFDocument对象POI是apache提供的可以操作word文档的第三方jar。POI能操作word是使用XWPFDocument对象。
- XWPFDocument对象可以解析docx文件,在XWPFDocument对象通过输入流解析docx的时候,会获取到docx文档中的各种对象,例如表格,段落,图片等,通过操作XWPFDocument对象就可以修改模板内容
- XWPFDocument API结构org.apache.poi.xwpf.usermodel.XWPFDocument
- XWPFDocument 提供write(OutputStream stream)方法将修改后的对象重新写入xml并生成新的docx
通过XWPFDocument 可以获得的docx中的各种对象
要具体操作通过XWPFDocument 可以获得的docx中的各种对象,我们离不开一个对象为XWPFRun对象,API结构org.apache.poi.xwpf.usermodel.XWPFRun。其描述为:XWPFRun object defines a region of text with a common set of properties。通过描述我们不难理解其作用为设置文本对象的各种属性。
通过XWPFDocument 获取对象
//解析docx模板并获取document对象
XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(inputUrl));
//获取整个文本对象
List<XWPFParagraph> allParagraph = document.getParagraphs();
//获取整个表格对象
List<XWPFTable> allTable = document.getTables();
//获取图片对象
XWPFPictureData pic = document.getPictureDataByID("PICId");
下面demo的输出可以看出我们操作文本对象,成功获取了文本内容
@Component("xWPRUNTest")
public class XWPRUNTest {
//模板文件地址
private static String inputUrl = "C:\\Users\\zhihe\\Desktop\\demo\\001.docx";
public void runTest(){
try {
//解析docx模板并获取document对象
XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(inputUrl));
//获取整个文本对象
List<XWPFParagraph> allParagraph = document.getParagraphs();
//获取XWPFRun对象输出整个文本内容
StringBuffer tempText = new StringBuffer();
for (XWPFParagraph xwpfParagraph : allParagraph) {
List<XWPFRun> runList = xwpfParagraph.getRuns();
for (XWPFRun xwpfRun : runList) {
tempText.append(xwpfRun.toString());
}
}
System.out.println(tempText.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
在这里发现操作文本对象的时候并没有获取到表格文本,所以如果我们需要获取到表格文本还需要另外的操作
@Component("xWPRUNTableTest")
public class XWPRUNTableTest {
//模板文件地址
private static String inputUrl = "C:\\Users\\zhihe\\Desktop\\demo\\001.docx";
public void tableTest(){
try {
StringBuffer tableText = new StringBuffer();
//解析docx模板并获取doc