JAVA根据word模版使用poi导出word文档,包含图片、文字

模版word文件,内容和表格都已处理,保留了字体和样式,图片可以指定大小,docx类型的模版字段有问题的话,整个字段复制进去即可,不要手敲${}

在这里插入图片描述

生成的word文件

在这里插入图片描述

/**
 * word工具类
 *
 * @author lks
 * @date 2021/2/24 11:16
 */
public class WordUtils {
	//本地测试
	                    /**
                     * 模版图片规则:${img-上传图片-200-200}   
                     * img:代表是图片
                     * 上传图片:模版的字段
                     * 200:宽(像素),可自定义
                     * 200:高(像素),可自定义
                     */
    public static void main(String[] args) throws IOException {

        //docx本地
        Map<String, Object> map = new HashMap<>();
        map.put("姓名", "张三");
        map.put("上传图片", "https://smart-form-dev.oss-cn-beijing.aliyuncs.com/fillImg/150a3d39976ab324/1632644009526_%E5%9B%BE%E7%89%871.png");
        FileInputStream in = new FileInputStream("/Users/liangkesai/Downloads/1.docx");
        XWPFDocument docx = new XWPFDocument(in);
        //表格内容替换添加
        Iterator<XWPFTable> itTable = docx.getTablesIterator();
        while (itTable.hasNext()) {
            //表格中所有的行
            List<XWPFTableRow> rows = itTable.next().getRows();
            for (XWPFTableRow row : rows) {
                //获取每一行的格子
                List<XWPFTableCell> cells = row.getTableCells();
                for (XWPFTableCell cell : cells) {
                    if (cell != null) {
                        processParagraphs(cell.getParagraphs(), map);
                    }
                }
            }
        }
        //替换段落中的指定文字
        processParagraphs(docx.getParagraphs(), map);
        docx.write(new FileOutputStream("/Users/liangkesai/Downloads/4.doc"));


        //doc 本地,doc暂时不支持图片,只能做到文本替换
//        Map<String, Object> map = new HashMap<>();
//        map.put("姓名", "张三");
//        map.put("上传图片", "https://smart-form-dev.oss-cn-beijing.aliyuncs.com/fillImg/150a3d39976ab324/1632644009526_%E5%9B%BE%E7%89%871.png");
//        FileInputStream in = new FileInputStream("/Users/liangkesai/Downloads/1.docx");
//        HWPFDocument doc = new HWPFDocument(in);
//        Range range = doc.getRange();
//        for (Map.Entry entry : map.entrySet()) {
//            String key = "${" + entry.getKey() + "}";
//            range.replaceText(key, String.valueOf(entry.getValue()));
//        }
//        doc.write(new FileOutputStream("/Users/liangkesai/Downloads/4.doc"));


    }

    /**
     * 下载
     *
     * @param templateUrl
     * @param map
     * @param response
     * @param fileName
     */
    public static void downWordByTemplate(String templateUrl, Map<String, Object> map, HttpServletResponse response, String fileName) {
        //输出流
        OutputStream os = null;
        InputStream in = null;

        try {
            // 生成word文档并读取模板
            in = new URL(templateUrl).openStream();
            if (!templateUrl.endsWith("doc") && !templateUrl.endsWith("docx")) {
                throw new CustomException("文件类型错误");
            }
            if (templateUrl.endsWith("doc")) {
                HWPFDocument doc = new HWPFDocument(in);
                Range range = doc.getRange();
                for (Map.Entry entry : map.entrySet()) {
                    String key = "${" + entry.getKey() + "}";
                    range.replaceText(key, String.valueOf(entry.getValue()));
                }

                fileName = fileName + ".doc";
                response.reset();
                response.setContentType("application/msword");
                response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));

                os = response.getOutputStream();
                doc.write(os);

                doc.close();
            } else {
                XWPFDocument docx = new XWPFDocument(in);
                //表格内容替换添加
                Iterator<XWPFTable> itTable = docx.getTablesIterator();
                while (itTable.hasNext()) {
                    //表格中所有的行
                    List<XWPFTableRow> rows = itTable.next().getRows();
                    for (XWPFTableRow row : rows) {
                        //获取每一行的格子
                        List<XWPFTableCell> cells = row.getTableCells();
                        for (XWPFTableCell cell : cells) {
                            if (cell != null) {
                                processParagraphs(cell.getParagraphs(), map);
                            }
                        }
                    }
                }

                //替换段落中的指定文字
                processParagraphs(docx.getParagraphs(), map);

                fileName = fileName + ".docx";
                response.reset();
                response.setContentType("application/msword");
                response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));

                os = response.getOutputStream();
                docx.write(os);
                docx.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (in != null) {
                    in.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 替换文字和图片
     *
     * @param paragraphs
     * @param map
     */
    protected static void processParagraphs(List<XWPFParagraph> paragraphs, Map<String, Object> map) {
        for (XWPFParagraph paragraph : paragraphs) {
            List<XWPFRun> runs = paragraph.getRuns();
            for (XWPFRun run : runs) {
                String textTemp = StrUtil.subBetween(run.getText(run.getTextPosition()), "${", "}");

                if (StrUtil.isNotBlank(textTemp)) {
                    // 图片规则,${img-上传图片-200-200}   img-字段名-宽-高
                    if (textTemp.startsWith("img-")) {
                        String[] split = textTemp.split("-");
                        if (split.length == 4 && StrUtil.isNotBlank(split[1]) && map.containsKey(split[1])) {
                            try {
                                String imgurl = String.valueOf(map.get(split[1]));
                                String picType = null;
                                if (imgurl.contains(".")) {
                                    picType = imgurl.substring(imgurl.lastIndexOf(".") + 1);
                                }
                                byte[] bs = IOUtils.toByteArray(new URL(imgurl).openStream());
                                int width = Units.toEMU(Double.parseDouble(split[2]));
                                int height = Units.toEMU(Double.parseDouble(split[3]));
                                run.setText("", 0);
                                run.addPicture(new ByteArrayInputStream(bs), getPictureType(picType), "", width, height);
                            } catch (IOException | InvalidFormatException e) {
                                run.setText(String.valueOf(map.get(split[1])), 0);
                            }
                        }
                    } else {
                        if (map.containsKey(textTemp)) {
                            run.setText(String.valueOf(map.get(textTemp)), 0);
                        }
                    }
                }
            }
        }
    }


    /**
     * 根据图片类型,取得对应的图片类型代码
     *
     * @param picType
     * @return int
     */
    private static int getPictureType(String picType) {
        int res = Document.PICTURE_TYPE_JPEG;
        if (picType != null) {
            if (picType.equalsIgnoreCase("png")) {
                res = Document.PICTURE_TYPE_PNG;
            } else if (picType.equalsIgnoreCase("dib")) {
                res = Document.PICTURE_TYPE_DIB;
            } else if (picType.equalsIgnoreCase("emf")) {
                res = Document.PICTURE_TYPE_EMF;
            } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) {
                res = Document.PICTURE_TYPE_JPEG;
            } else if (picType.equalsIgnoreCase("wmf")) {
                res = Document.PICTURE_TYPE_WMF;
            } else {
                res = Document.PICTURE_TYPE_JPEG;
            }
        }
        return res;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赛赛liangks

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值