浏览器下载poi-tl生成的word文件
1、生成单个word,直接写入response到浏览器下载
//浏览器单个下载File sourceFile = new File(templatePath + "/" + fileName + ".docx");try {//创建行循环策略LoopRowTableRenderPolicy rowTableRenderPolicy = new LoopRowTableRenderPolicy();//告诉模板引擎,绑定行循环策略Configure configure = Configure.builder().bind("imgList", rowTableRenderPolicy) //附表1.build();XWPFTemplate template = XWPFTemplate.compile(sourceFile,configure).render(exportMap);ServletOutputStream outputStream = response.getOutputStream();response.setCharacterEncoding("UTF-8");// 对文件名进行编码处理中文问题exportFileName = new String(exportFileName.getBytes(), StandardCharsets.UTF_8);response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(exportFileName, "UTF-8"));template.write(outputStream);outputStream.close();template.close();} catch (Exception e) {e.printStackTrace();}
2、生成多个word文件保存到本地,生成压缩包,再写入response到浏览器下载zip文件
(1)生成word文件到本地,并返回保存文件的目录
private String saveReportExportWord(String templatePath, String fileName, Map<String, Object> exportParams,HttpServletRequest request, HttpServletResponse response, String uuid) {//创建行循环策略LoopRowTableRenderPolicy rowTableRenderPolicy = new LoopRowTableRenderPolicy();//告诉模板引擎,绑定行循环策略Configure configure = Configure.builder().bind("imgList", rowTableRenderPolicy) //附表1.build();String saveFilePath = "";// 校验Assert.notNull(templatePath, "模板路径不能为空");Assert.notNull(fileName, "导出文件名不能为空");Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式");//模板文件File sourceFile = new File(templatePath);// 生成文档保存目录String savePath = uploadedReportPath;String subPathPrefix = uuid + "/";savePath += "/" + subPathPrefix;// 判断目录是否存在,不存在创建File dir = new File(savePath);if (!dir.exists()) {dir.mkdirs();}// 将文档保存到指定目录OutputStream fos = null;try {saveFilePath = savePath + fileName;fos = new FileOutputStream(saveFilePath);XWPFTemplate.compile(sourceFile, configure).render(exportParams).writeAndClose(fos);} catch (Exception e) {e.printStackTrace();} finally {// 关闭输出流try {fos.close();} catch (IOException e) {e.printStackTrace();}}return savePath;}
2.将word文件目录打包返回到response到浏览器下载
//returnSavePath 是存放生成的word的文件夹if (StringUtils.isNotEmpty(returnSavePath)) {File zip = ZipUtil.zip(returnSavePath);try {ServletOutputStream outputStream = response.getOutputStream();FileInputStream ins = new FileInputStream(zip);response.setCharacterEncoding("UTF-8");// 对文件名进行编码处理中文问题fileName = new String(fileName.getBytes(), StandardCharsets.UTF_8);response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".zip", "UTF-8"));byte[] b = new byte[1024];int length;while ((length = ins.read(b)) > 0) {outputStream.write(b, 0, length);}outputStream.close();ins.close();} catch (Exception e) {e.printStackTrace();}//删除临时文件zip.delete();//压缩包File childFile = new File(returnSavePath); //生成的文件try {deleteDirectory(childFile);} catch (IOException e) {e.printStackTrace();}}