1.使用Poi-tl,添加依赖
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.0.0</version>
</dependency>
poi-tl是一个java的模板引擎。
GitHub主页:https://github.com/Sayi/poi-tl
完整文档地址
2.生成模板,并输出到out流提供下载
package com.deepoove.hooks.web.controller;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.RequestContextUtils;
import com.deepoove.poi.XWPFTemplate;
@RestController
@RequestMapping("/download")
public class DownloadController {
@SuppressWarnings("serial")
@RequestMapping("/word")
public void hook(HttpServletRequest request, HttpServletResponse response) throws IOException {
Resource resource = RequestContextUtils.getWebApplicationContext(request).getResource("plugin.docx");
Map<String, Object> datas = new HashMap<String, Object>() {
{
put("text", "text value");
}
};
//使用poi-tl模板引擎渲染word模板
XWPFTemplate template = XWPFTemplate.compile(resource.getFile()).render(datas);
String contentType="application/octet-stream";
response.setContentType(contentType);
//设置response的头信息
response.setHeader("Content-disposition","attachment;filename=\""+"XXX.docx"+"\"");
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
//输出流,便于在servlet下载
ByteArrayOutputStream baos = new ByteArrayOutputStream();
template.write(baos);
baos.flush();
template.close();
bos.write(baos.toByteArray());
bos.close();
baos.close();
return;
}
}