需求查询数据放入word模板中并在前端导出下载

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

代码

    @PostMapping("/practiceAppr")
    public AjaxResult practiceAppr(OutputStream outputStream, @RequestBody ExportToExcelParamDto paramDto) {

        //查询数据  ExportToWordByPracticeApprDto 为定义模板中的参数
        ExportToWordByPracticeApprDto app= baseService.practiceApprExport(paramDto);
        
                try {
                    //获取模板文件
                    try (InputStream is = TrActivityGroupServiceImpl.class.getClassLoader().getResourceAsStream("word/导出模板A4.docx")
                    ) {
                        try (XWPFDocument doc = new XWPFDocument(is)
                        ) {
                            Map<String, Object&gt; replaceMap = BeanUtil.beanToMap(app);
                            Map<String, Object&gt; resultMap = new HashMap<&gt;();
                            //word中的占位符格式是{{}}
                            replaceMap.forEach((placeholder, replacement) -&gt; resultMap.put("{{" + placeholder + "}}", replacement));
                            //处理文件替换参数为实际值
                            replacePlaceholders(doc, resultMap);
                            doc.write(outputStream);
                            outputStream.close();
                            is.close();
                        }
                    }
                } catch (Exception e) {
                    logger.error("文件导出错误{}", e.getMessage());
                }
          
        return null;
    }



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为图片的后缀 .png
                                            ImageIO.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);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

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

原文地址:https://blog.csdn.net/qq_29958413/article/details/134531381

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_7601.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注