经常会遇到这样需求,写一个导出功能,进行word模板格式进行导出,数据库相应数据回填到word模板中,再对这个模板进行导出功能。如果一次性需要导出多个模板情况下,就要对多个进行压缩成一个压缩包再一次性导出。
废话不多说直接上代码:
需要导入相应jar包:
controller层:
@GetMapping(value = "/export") public void export(HttpServletResponse response) { try { taskServic.exportWordZip(response); } catch (Exception e) { logger.error("导出失败", e); } }
service层:
/** * 获取当前系统的临时目录 */ public final static String SRC_PATH = System.getProperty("java.io.tmpdir");
/** * 导出(zip) * @param response */ public void exportWordZip( HttpServletResponse response) { Listfiles = new ArrayList<>(); //数据库查出来数据--模拟写个测试数据 DemoVO vo = new DemoVO(); vo.setName("测试模板数据"+System.currentTimeMillis()); String zipFileName = "测试模板数据"; // 动态获取模板名称 String templateName = "demo.docx"; //模板 String fileName = System.currentTimeMillis()+""; //要写入模板里数据 String tempFileTemplate = generate(vo, templateName, fileName); if (tempFileTemplate != null) { files.add(new File(tempFileTemplate)); } //压缩包下载 if (files != null) { zipDownload(response, zipFileName + "_" + System.currentTimeMillis() + ".zip", files); } }
/** * 生成-模板-数据写入.docx文件模板 * * @return */ public String generate(Object object, String templateName, String fileName) { // 获取当前系统的临时目录 String filePath = SRC_PATH; String addTimeFileName = fileName; //存储的文件路径 File.separator String storeFilePath = filePath + addTimeFileName; String docxFilePath = storeFilePath + ".docx"; //后缀 String suffix = ".docx"; XWPFTemplate template = null; try (OutputStream os = new FileOutputStream(docxFilePath); InputStream inputStream = new ClassPathResource("/templates/" + templateName).getInputStream()) { DemoVO vo = (DemoVO) object; template = XWPFTemplate.compile(inputStream).render(new HashMap() {{ put("name", vo.getName()); }}); template.write(os); os.flush(); return storeFilePath + suffix; } catch (Exception e) { // logger.error("生成模板失败", e); } finally { if (template != null) { try { template.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; }
/** * zip打包下载 * * @param response * @param zipFileName * @param fileList */ public void zipDownload(HttpServletResponse response, String zipFileName, ListfileList) { // zip文件路径 String zipPath = ZipDownloadUtil.FILE_PATH + zipFileName; try { //创建zip输出流 try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath))) { //声明文件集合用于存放文件 byte[] buffer = new byte[]; //将文件放入zip压缩包 for (int i = 0; i < filelist.size i file file='fileList.get(i);' try fileinputstream fis='new' fileinputstreamfile out.putnextentrynew zipentryfile.getname int len zip while len='fis.read(buffer))'> 0) { out.write(buffer, 0, len); } out.closeEntry(); } file.delete(); } } //下载zip文件 ZipDownloadUtil.downFile(response, zipFileName); } catch (Exception e) { // logger.error("文件下载出错", e); } finally { // zip文件也删除 fileList.add(new File(zipPath)); ZipDownloadUtil.deleteFile(fileList); } }
看下一个模板内容
demo.docx
看下导出效果:
完美收工。