springboot 使用POI解决word模板导出下载
我这边例子是给定工单模板,根据业务要求查出来具体的工单信息,并填充到工单模板里面,然后再下载;具体实现代码如下
word模板
其中花括号表示占位符,里面字段代表需要映射的key值。模板写好之后放到系统自己设定的位置
maven依赖:
cn.afterturn
easypoi-web
4.1.3
org.apache.commons
commons-lang3
3.9
cn.afterturn
easypoi-base
3.0.3
cn.afterturn
easypoi-annotation
3.0.3
工具类:
package com.zhhl.control.util.file;
import cn.afterturn.easypoi.word.WordExportUtil;
import cn.afterturn.easypoi.word.entity.MyXWPFDocument;
import io.jsonwebtoken.lang.Assert;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;
public class WordUtils {
/**
* 导出word
* 第一步生成替换后的word文件,只支持docx
* 第二步下载生成的文件
* 第三步删除生成的临时文件
* 模版变量中变量格式:{{foo}}
* @param is word模板
* @param temDir 生成临时文件存放地址
* @param fileName 文件名
* @param params 替换的参数
* @param request HttpServletRequest
* @param response HttpServletResponse
*/
public static void exportWord(InputStream is, String temDir, String fileName, Map params, HttpServletRequest request, HttpServletResponse response) {
Assert.notNull(is,"模板路径不能为空");
Assert.notNull(temDir,"临时文件路径不能为空");
Assert.notNull(fileName,"导出文件名不能为空");
Assert.isTrue(fileName.endsWith(".doc"),"word导出请使用doc格式");
if (!temDir.endsWith("/")){
temDir = temDir + File.separator;
}
File dir = new File(temDir);
if (!dir.exists()) {
dir.mkdirs();
}
try {
String userAgent = request.getHeader("user-agent").toLowerCase();
if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
}
MyXWPFDocument doc = new MyXWPFDocument(is);
WordExportUtil.exportWord07(doc, params);
String tmpPath = temDir + fileName;
FileOutputStream fos = new FileOutputStream(tmpPath);
doc.write(fos);
// 设置强制下载不打开
response.setCharacterEncoding("UTF-8");
response.setContentType("application/force-download");
// 设置文件名
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
OutputStream out = response.getOutputStream();
doc.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
delFileWord(temDir,fileName);//这一步看具体需求,要不要删
}
}
/**
* 删除零时生成的文件
*/
public static void delFileWord(String filePath, String fileName) {
File file = new File(filePath + fileName);
File file1 = new File(filePath);
file.delete();
file1.delete();
}
}
控制层代码:
@ApiOperation(value = "工单导出", notes = "工单导出")
@PostMapping(value = "/exportWord")
public void exportWord(@RequestBody Map idMap, HttpServletRequest request, HttpServletResponse response) throws ServiceProviderException {
Map params = new HashMap<>();
/*//如果word模板地址放在 webapp下采用如下方式获取word模板路径:
//表示到项目的根目录(webapp)下,要是想到目录下的子文件夹,修改"/"即可
String path = request.getSession().getServletContext().getRealPath("/");*/
//word模板地址放在src/main/resources/下,因为配置过静态资源映射,所以采用如下方式获取项目中的word模板地址:
//String templatePath = "static/template/workOrdersTemplate.docx";//word模板地址
InputStream is = this.getClass().getResourceAsStream("/static/template/workOrdersTemplate.docx");
FrameWorkOrders frameWorkOrders = frameWorkOrdersProvider.findById(idMap.get("id").toString());
if(frameWorkOrders != null){
// 渲染文本
params.put("workOrderNum", frameWorkOrders.getWorkOrderNum());
params.put("faultDesc", frameWorkOrders.getFaultDesc());
//上报故障时间
Date faultTime = frameWorkOrders.getFaultTime();
if(faultTime != null){
params.put("faultTimeStr", DateUtil.format(faultTime,Constants.DATE_FORMAT.E_DATE_FORMAT_SECOND));
}else {
params.put("faultTimeStr", "-");
}
Date sendTime = frameWorkOrders.getSendTime();
if(sendTime != null){
params.put("sendTimeStr", DateUtil.format(sendTime,Constants.DATE_FORMAT.E_DATE_FORMAT_SECOND));
}else {
params.put("sendTimeStr", "-");
}
//限办时间
Date limitTime = frameWorkOrders.getLimitTime();
if(limitTime != null){
params.put("limitTimeStr", DateUtil.format(faultTime,Constants.DATE_FORMAT.E_DATE_FORMAT_SECOND));
}else {
params.put("limitTimeStr", "-");
}
//所在道路
if(frameWorkOrders.getPlaceRoad() != null){
if(frameBaseDataValueMapper.findByTagIdValue(frameWorkOrders.getPlaceRoad(),"04C8447D0FA8489BB55AE67260CF6144")!= null){
params.put("placeRoadStr", frameBaseDataValueMapper.findByTagIdValue(frameWorkOrders.getPlaceRoad(),"04C8447D0FA8489BB55AE67260CF6144"));
}else {
params.put("placeRoadStr", frameBaseDataValueMapper.findByTagIdValue(frameWorkOrders.getPlaceRoad(),"39D9559A75E840B89652DA4E9343173F"));
}
}else {
params.put("placeRoadStr","-");
}
if(frameWorkOrders.getDeptName() != null){
params.put("deptStr", frameDeptMapper.findById(frameWorkOrders.getDeptName()).getDeptName());
}else {
params.put("deptStr","-");
}
//问题大类和问题小类
if(frameWorkOrders.getProblemBigClass() != null){
params.put("problemBigClassStr", frameBaseDataValueMapper.findByTagIdValue(frameWorkOrders.getProblemBigClass(),"457845454FDFEEWR4544545778"));
}else {
params.put("problemBigClassStr","-");
}
if(frameWorkOrders.getProblemSmallClass() != null){
params.put("problemSmallClassStr", frameBaseDataValueMapper.findByTagIdValue(frameWorkOrders.getProblemSmallClass(),"ED537DC46AA74301B1EE111CBE598D43"));
}else {
params.put("problemSmallClassStr","-");
}
//派发人
if(frameWorkOrders.getSendPerson() != null){
params.put("sendPersonStr", frameUserMapper.findById(frameWorkOrders.getSendPerson()).getUserName());
}else {
params.put("sendPersonStr","-");
}
//现场负责人
if(frameWorkOrders.getOperationPerson() != null){
params.put("operationPersonStr", frameUserMapper.findById(frameWorkOrders.getOperationPerson()).getUserName());
}
params.put("FaultExplain", frameWorkOrders.getFaultExplain() == null? "-":frameWorkOrders.getFaultExplain());
// 渲染图片
//WordImageEntity image = new WordImageEntity();
// //image.setHeight(120);
// //image.setWidth(120);
//image.setUrl("D:\\cssTest\\square.png");
//image.setType(WordImageEntity.URL);
//params.put("picture", image);
// TODO 渲染其他类型的数据请参考官方文档
String temDir="opt/mimi/"+ File.separator+"file/word/"; ;//生成临时文件存放地址
// 生成的word格式
String formatSuffix = ".doc";
// 拼接后的文件名
String fileName = "市政照明设施维修派工单" + formatSuffix;//文件名 带后缀
//导出word
WordUtils.exportWord(is, temDir, fileName, params, request, response);
}
}
测试下载
最开始出现的问题是用poi实现word模板套打功能,本地windows环境可以实现,打包部署到linux报错,后来发现是因为项目打包之后会将模板乱码(报错ruxia),导致读取失败,解决方法把linux服务器上的模板删掉,重新上传到linux上目录位置。
java.io.IOException: Failed to read zip entry source
at org.apache.poi.openxml4j.opc.ZipPackage.
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:342)
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37)
at org.apache.poi.xwpf.usermodel.XWPFDocument.
at cn.afterturn.easypoi.word.entity.MyXWPFDocument.
at com.zhhl.control.util.file.WordUtils.exportWord(WordUtils.java:50)
at com.zhhl.control.restful.itopem.FrameWorkOrdersRestServer.exportWord(FrameWorkOrdersRestServer.java:149)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:108)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1591)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.util.zip.ZipException: invalid code lengths set
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:164)
at java.util.zip.ZipInputStream.read(ZipInputStream.java:194)
at org.apache.poi.openxml4j.util.ZipSecureFile$ThresholdInputStream.read(ZipSecureFile.java:213)
at java.io.FilterInputStream.read(FilterInputStream.java:107)
at org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource$FakeZipEntry.
at org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource.
at org.apache.poi.openxml4j.opc.ZipPackage.
... 60 more
其实是个小问题,最开始没有意识到是模板打包后出现了问题,希望可以当做参考