从别人那里看的,结果后来发版到服务器导出时报错,访问不到模板路径位置,后来改成了。这里我自己整理一下
重点:解决 访问不到Word模板路径
//word模板文件流 这种方法不会在linux上或者jar启动失效InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("static/template/test2.docx");
1.引入依赖,添加到pom.xml文件
<!-- word导出 --><dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</artifactId><version>1.7.3</version></dependency><!-- 上面需要的依赖--><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency>
2.新建一个controller用于测试,下图是我的模板路径(声明一下我这里是springboot项目) src/main/resources/static/template/test2.docx
@RequestMapping("/auth/exportWord/")@RestControllerpublic class ExportWordController {/*** 导出word --- poi-tl(包含动态表格)*/@RequestMapping("/exportDataWord3")public void exportDataWord3(HttpServletResponse response) throws IOException {try {//组装动态表格列表数据List<Map<String,Object>> detailList = new ArrayList<Map<String,Object>>();for (int i = 0; i < 5; i++) {Map<String,Object> detailMap = new HashMap<String, Object>();detailMap.put("procName", "总装" + i + "工序");//工序detailMap.put("reportName", "隔壁老王" + i);//装配人员detailMap.put("materialName","压缩机组件" + i);detailMap.put("number","0817" + i);detailMap.put("installNum",i + "台");detailList.add(detailMap);}//word模板文件流 这种方法不会在linux上或者jar启动失效InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("static/template/test2.docx");//渲染表格HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();Configure config = Configure.newBuilder().bind("detailList", policy).build();XWPFTemplate template = pile( inputStream, config).render(new HashMap<String, Object>() {{put("detailList", detailList);put("predefine2", "AR系列");put("no","0803001");put("spec","AR-5-N");put("planStartDate", "-9-10 16:11:00");put("customerName","非洲私立医院");put("salesorderNo","ATCL21-023");put("test1","10088200");put("test2","隔壁老王");put("test3","隔壁老王");}});//生成文件名String fileName = new Date().getTime() + ".docx";//文件名 带后缀// 设置强制下载不打开response.setContentType("application/force-download");// 设置文件名,解决中文乱码问题response.setCharacterEncoding("utf-8");response.addHeader("Content-Disposition","attachment; filename=\"" + new String("记录跟踪单".getBytes("gbk"),"iso8859-1") + fileName + "\"");OutputStream out = response.getOutputStream();template.write(out);out.flush();out.close();template.close();} catch (Exception e) {e.printStackTrace();}}}
3.Word模板样式:
4.导出结果:
AR系列氧气机生产记录跟踪单
SAET-7.5-027/C N0.:0803001
整机编号:10088200 验证:隔壁老王 批准:隔壁老王