maven引用
<dependencies>
<!--word操作工具类-->
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.6.0-beta1</version>
</dependency>
<!-- javaEEApi,如果部署在tomcat容器中可以添加配置:<scope>provided</scope> -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<!--poi对excel2007以上版本的支持 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
</dependencies>
代码实现
//java项目 www.fhadmin.org
//需要保存的文件名/保存地址
String fileName = null;
fileName = talk.getSid() + "-" + talk.getName();
//将模板word转化为stream
InputStream is = this.getClass().getResourceAsStream("/templates/talk/ceshi.docx");
//将数据对象转为HashMap 或者自己组装
HashMap<String,String > dataMap = JSONObject.parseObject(JSONObject.toJSONString(talk),HashMap.class);
XWPFTemplate xwpfTemplate = null;
//实际使用代码-----
//数据替换
xwpfTemplate = XWPFTemplate
.compile(is)
.render(dataMap);
//数据保存
xwpfTemplate.writeToFile(fileName+".docx");