当前位置: 首页 > news >正文

Java查询多条数据放入word模板 多个word文件处理成zip压缩包并在前端下载.zip文件

 需求:Java查询多条数据放入word模板 多个word文件处理成zip压缩包并在前端下载.zip文件

解决方法:在模板的位置定义参数如 {{name}}  {{age}}等等,使用 poi 处理

伪代码:

    @PostMapping("/exportPracticeAppr")public String exportPracticeAppr(HttpServletResponse response, @RequestBody ExportToExcelParamDto paramDto) throws IOException {//查询数据 ExportToWordByPracticeApprDto为模板中的参数List<ExportToWordByPracticeApprDto> practiceApprExport = baseService.practiceApprExport(paramDto);if (practiceApprExport != null && !practiceApprExport.isEmpty()) {// 创建一个zip文件,并打开一个ZipOutputStream来写入文件FileOutputStream fos = new FileOutputStream(paramDto.getActivityName() + "demo.zip");ZipOutputStream zos = new ZipOutputStream(fos);try {//获取word模板文件InputStream resourceAsStream = TrActivityGroupServiceImpl.class.getClassLoader().getResourceAsStream("word/导出模板.docx");XWPFDocument doc = new XWPFDocument(Objects.requireNonNull(resourceAsStream));//循环处理文件for (ExportToWordByPracticeApprDto apprDto : practiceApprExport) {Map<String, Object> replaceMap = BeanUtil.beanToMap(apprDto);Map<String, Object> resultMap = new HashMap<>();replaceMap.forEach((placeholder, replacement) -> resultMap.put("{{" + placeholder + "}}", replacement));replacePlaceholders(doc, resultMap);// 将Word文档保存为临时文件File tempFile = File.createTempFile("demo", DOCX);FileOutputStream tempOut = new FileOutputStream(tempFile);doc.write(tempOut);tempOut.close();// 将临时文件添加到zip文件中  表示压缩包中的文件名称 aa.docxZipEntry zipEntry = new ZipEntry("aa.docx");zos.putNextEntry(zipEntry);FileInputStream fis = new FileInputStream(tempFile);IOUtils.copy(fis, zos);fis.close();zos.closeEntry();tempFile.delete();}// 关闭zip文件输出流zos.close();doc.close();} catch (Exception e) {logger.error("文件导出错误{}", e.getMessage());}}// 返回zip文件内容byte[] zipBytes = IOUtils.toByteArray(Files.newInputStream(Paths.get("demo.zip")));response.reset();response.setContentType("application/zip");response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("demo.zip", "UTF-8"));response.setContentLength(zipBytes.length);OutputStream out = response.getOutputStream();out.write(zipBytes);out.flush();out.close();return "redirect:/";}private void replacePlaceholders(XWPFDocument document, Map<String, Object> placeholders) throws IOException, InvalidFormatException {//处理普通word文字 不包含表格for (XWPFParagraph paragraph : document.getParagraphs()) {List<XWPFRun> runs = paragraph.getRuns();for (XWPFRun run : runs) {String text = run.getText(0);if (text != null) {for (Map.Entry<String, Object> entry : placeholders.entrySet()) {if (text.contains(entry.getKey())) {text = text.replace(entry.getKey(), entry.getValue() != null ? (String) entry.getValue() : "");run.setText(text, 0);}}}}}// 处理替换表格中的占位符for (XWPFTable table : document.getTables()) {for (XWPFTableRow row : table.getRows()) {for (XWPFTableCell cell : row.getTableCells()) {for (XWPFParagraph paragraph : cell.getParagraphs()) {List<XWPFRun> runs = paragraph.getRuns();for (XWPFRun run : runs) {String text = run.getText(0);if (text != null) {for (Map.Entry<String, Object> entry : placeholders.entrySet()) {if (text.contains(entry.getKey())) {//获取、处理图片略......int format = XWPFDocument.PICTURE_TYPE_PNG;//图片地址BufferedImage image = ImageIO.read(new URL(value));ByteArrayOutputStream outputStream = new ByteArrayOutputStream();//suffix为图片的后缀 .pngImageIO.write(image, suffix, outputStream);byte[] imageBytes = outputStream.toByteArray();//后两个参数是宽高run.addPicture(new ByteArrayInputStream(imageBytes), format, fileName, Units.toEMU(80), Units.toEMU(40));//替换文字  图片和文字如果都展示text = text.replace(entry.getKey(), entry.getValue() != null ? (String) entry.getValue() : "");run.setText(text, 0);}}}}}}}}}

最后前端处理进行下载即可。

http://www.lryc.cn/news/240129.html

相关文章:

  • PC8223(CC/CV控制)高耐压输入5V/3.4A同步降压电路内建补偿带恒流恒压输出
  • 【webrtc】ModuleRtpRtcpImpl2: RtpRtcp DEPRECATED_Create 废弃了
  • 八股文面试day5
  • 数据处理生产环境_获取当前日期的前一天日期
  • 5.过滤敏感词 + 发布帖子 + 帖子详情
  • 大数据基础设施搭建 - Flume
  • 华为OD机试 - 找朋友(Java 2023 B卷 100分)
  • ESP32 MicroPython 颜色及二维码识别⑫
  • 数据结构与算法编程题15
  • 基于Mapmost Alpha工具快速搭建3D场景可视化大屏
  • OpenAI再次与Sam Altman谈判;ChatGPT Voice正式上线
  • 技术是增长关键驱动!传音控股新专利亮相,看未来手机趋势
  • C# - Opencv应用(2) 之矩阵Mat使用[矩阵创建、图像显示、像素读取与赋值]
  • 执行npm的时候报权限问题的解决方案
  • 【实用】PPT没几页内存很大怎么解决
  • 【Docker】从零开始:8.Docker命令:Commit提交命令
  • 【深度学习】神经网络术语:Epoch、Batch Size和迭代
  • 谈谈你对mvc和mvvm的理解
  • C语言每日一题(35)有效的括号
  • 【DevOps】Git 图文详解(七):标签管理
  • BootStrap【表格二、基础表单、被支持的控件、表单状态】(二)-全面详解(学习总结---从入门到深化)
  • 亿赛通电子文档安全管理系统UploadFileFromClientServiceForClient接口存在任意文件上传漏洞 附POC
  • SPSS系统聚类
  • 【ArcGIS Pro微课1000例】0033:ArcGIS Pro处理cad数据(格式转换、投影变换)
  • 【小呆的力学笔记】有限元专题之循环对称结构有限元原理
  • 云端导览,数字互动 | 拓世法宝AI数字人一体机助力全新旅游时代
  • PTA-快速幂
  • 【深度学习】Transformer简介
  • Linux 是否被过誉了?
  • 【SpringBoot篇】Spring_Task定时任务框架