poi 读写word文档并下载文件
**本文主要介绍如何将数据导入word文档模板,根据需要动态拼接列,并将模板下载下来
1)首先需要导入依赖包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.0.2-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
2)后台读入word模板
--word模板中写入数据的部分需要画一个表格,利用表格样式来导入数据
--pathT 是模板的绝对路径
--table.next() 获取模板里面的表格
--调用table的getRows方法来获取表格所有的行
public static void insertRow(XWPFTable table, int copyrowIndex, int newrowIndex) {
// 在表格中指定的位置新增一行
XWPFTableRow targetRow = table.insertNewTableRow(newrowIndex);
// 获取需要复制行对象
XWPFTableRow copyRow = table.getRow(copyrowIndex);
//复制行对象
targetRow.getCtRow().setTrPr(copyRow.getCtRow().getTrPr());
//或许需要复制的行的列
List<XWPFTableCell> copyCells = copyRow.getTableCells();
//复制列对象
XWPFTableCell targetCell = null;
for (int i = 0; i < copyCells.size(); i++) {
XWPFTableCell copyCell = copyCells.get(i);
targetCell = targetRow.addNewTableCell();
targetCell.getCTTc().setTcPr(copyCell.getCTTc().getTcPr());
if (copyCell.getParagraphs() != null && copyCell.getParagraphs().size() > 0) {
targetCell.getParagraphs().get(0).getCTP().setPPr(copyCell.getParagraphs().get(0).getCTP().getPPr());
if (copyCell.getParagraphs().get(0).getRuns() != null
&& copyCell.getParagraphs().get(0).getRuns().size() > 0) {
XWPFRun cellR = targetCell.getParagraphs().get(0).createRun();
cellR.setBold(copyCell.getParagraphs().get(0).getRuns().get(0).isBold());
}
}
}
}
}
--利用这个方法可以在设定的位置添加新的一行,并复制一行的样式作为他的样式
注意:不能直接用XWPFTable自带的addRow或者insertNewTableRow方法,虽然也可以添加新一行,但是在赋值时会出问题,导入的值会一直赋给样本行,通过上述办法可以解决
3)将数据写入word模板
--遍历所有的行,下标从0开始,取到我们所需要的行中的单元格,就可以给单元格添加样式及内容
4)下载文档
--数据写入到模板里面后,将文件流出到输出流,输出到浏览器,下载文件
--我前台使用的是ext.js的download方法,直接传参请求后台就可以了
http://poi.apache.org/apidocs/dev/org/apache/poi/xwpf/usermodel/XWPFTable.html
--这个连接是关于XWPFTable的各种属性、方法的文档