1 Maven依赖
<!-- EasyPoi文档处理工具 -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.4.0</version>
</dependency>
<!-- JFreeChart图表库 -->
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.5.3</version>
</dependency>
<!-- Hutool工具包 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.6.2</version>
</dependency>
2 调试代码
/**
* 替换内容
*
* @param response
* @throws IOException
*/
@GetMapping("/replaceContent")
public void replaceContent(HttpServletResponse response) {
try {
//读文件
ClassPathResource cpr = new ClassPathResource("/doc/模板.docx");
XWPFDocument document = new MyXWPFDocument(cpr.getInputStream());
//生成文本内容Map
Map<String, Object> contentMap = new HashMap<>();
contentMap.put("xudongmaster1", "旭东怪1");
contentMap.put("xudongmaster2", "旭东怪2");
//图例名称列表
List<String> legendNameList = new ArrayList<>(Arrays.asList("一级", "二级", "三级", "四级", "五级"));
//数据列表
List<Object> dataList = new ArrayList<>(Arrays.asList(1, 3, 5, 6, 2));
//生成饼图数据
byte[] chartBytes = GenerateChartUtil.createPieChart("各级占比情况", legendNameList, dataList
, 300, 400, JFreeChartUtil.createChartTheme("宋体"));
//将饼图数据变成图片
ImageEntity image = new ImageEntity();
//设置高度
image.setHeight(400);
//设置宽度
image.setWidth(300);
//类型
image.setType(ImageEntity.Data);
image.setData(chartBytes);
contentMap.put("chart", image);
//替换文本内容
WordExportUtil.exportWord07(document, contentMap);
//返回流
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + new String("模板.docx".getBytes("utf-8"), "ISO-8859-1"));
OutputStream outputStream = response.getOutputStream();
document.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
3 模板文件
模板路径:
模板内容:
4 调试结果
注:
(1)模板中的替换标记必须以{{开始,以}}结尾,同时替换标记最好先在记事本中输入好,在复制到Word文档中,否则会出现内容替换失败的情况。
(2)GenerateChartUtil、JFreeChartUtil的源码请查看以下博客。