本文通过简单介绍几个示例 实现 word简单导出
①maven引用
<dependency> <groupId>com.deepoove</groupId> <artifactId>poi-tl</artifactId> <version>1.9.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency>
②word导出公共方法
public static void exportWordToPath(@NotNull String templateName,
@NotNull Map dataMap,
@NotNull HttpServletResponse response, String fileName) throws IOException {
XWPFTemplate xwpfTemplate = null;
OutputStream outputStream = response.getOutputStream();
try {
ListRenderPolicy policy = new ListRenderPolicy();
// 配置
Configure config = Configure.newBuilder().bind("yqst", policy).build();
InputStream inputStream = getTemplateFile(templateName);
// 编译模板,填充数据
xwpfTemplate = XWPFTemplate
.compile(inputStream, config)
.render(dataMap);
//设置Http响应头告诉浏览器下载这个附件
fileName = new String(fileName.getBytes(), StandardCharsets.ISO_8859_1);
response.setHeader("Content-Disposition", "attachment;Filename=" + fileName + ".docx");
response.setContentType("application/octet-stream");
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
xwpfTemplate.write(toClient);
toClient.flush();
} catch (IOException e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
throw new RuntimeException("生成文件失败!");
} finally {
if (xwpfTemplate != null) {
xwpfTemplate.close();
}
outputStream.close();
}
}
③导出示例
@GetMapping("/exportWord")
public void exportWord(HttpServletResponse response) throws IOException {
Map<String, Object> map = new HashMap<>();
//简单的文字导出
map.put("name","这是一个简单的导出");
//list导出 config需绑定 对象
List<Object> list =new ArrayList<>();
Style style = new Style();
style.setBold(true);
style.setColor("FF0040");
style.setFontSize(15);
/**
* 可以对文字进行风格设置
*/
list.add(new TextRenderData("听妈妈的话",style));
list.add(new TextRenderData("夜曲"));
list.add(new TextRenderData("止战之殇"));
map.put("yqst", list);
//表格导出 textColor 可定义字体颜色 bgColor 可定义单元格背景颜色 center表示居中
RowRenderData rows0 = Rows.of("歌手", "专辑名称","主打歌").textColor("2E2E2E").bgColor("F4FA58").center().create();
RowRenderData rows1 = Rows.of("周杰伦", "范特西","爱在西元前").textColor("0040FF").bgColor("F8E0EC").center().create();
map.put("table", Tables.create(rows0,rows1));
WordExportUtil.exportWordToPath("simple.docx", map, response, "第一个导出示例");
}
④模板示例
看下导出结果:
有不懂的可以留言~