Java操作Word模板产生全新内容Word

10 篇文章 0 订阅
2 篇文章 0 订阅

1. spire.doc的jar引用

        首先我们需要用到国产word处理工具jar包spire.doc,可以通过maven仓库寻找,然后在pom文件中直接引用。

        此处需要注意,我们需要使用的是spire.doc.free(免费版的),切勿使用spire.doc(如果使用了,处理后的word文件第一页的顶部会出现红色的警告水印信息)

        如果不能直接从仓库引用到此jar,可以在仓库直接下载下来后,手动存放与本地仓库中,处理方式详见本人的另一个帖子: 本地Maven仓库导入外部jar

2. 编辑模板内容,编辑后如下(示例,仅供参考):

 2.1 测试替换文字内容

/**
     * 替换文档中的制定文字
     *
     * @param inFilePath 文件存放全路径
     * @param map        要替换的内容(key为要替换的内容,value为要替换成的内容)
     * @return 产生的新文件存放地址
     * @throws FileNotFoundException
     */
    public static String replaceText(String inFilePath, Map<String, String> map) throws FileNotFoundException {
        Document doc = new Document(inFilePath);
//        doc.loadFromFile(inFilePath);
//        InputStream in = new BufferedInputStream(new FileInputStream(inFilePath));
//        doc.loadFromStream(in, FileFormat.Docx);
        map.forEach((k, v) -> {
            doc.replace(k, v, true, false);
        });
        String outFilePath = inFilePath.substring(0, inFilePath.lastIndexOf("."));
        outFilePath += "_副本.docx";
        doc.saveToFile(outFilePath, FileFormat.Docx);
        return outFilePath;
    }

    public static void main(String[] args) throws FileNotFoundException {
        String inFilePath = "C:\\Users\\DaiHaijiao\\Desktop/aaa.docx";
        Map<String, String> map = new HashMap<>(8);
        map.put("${name}", "张三");
        map.put("${car}", "配送员李四(15212345678)");
        map.put("${goodName}", "65寸小米电视机");
        map.put("${orderNo}", "NO.86418534741");
        map.put("${dateTime}", "2022-05-06 16:25:30");
        String outPath = WordUtils.replaceText(inFilePath, map);
        System.out.println(outPath);
    }

执行完后会输出新文件地址路径:

 打开此文件我们可以看到内容已经替换完成了

 2.2 替换图片(此处以替换那个假公章为例)

/**
     * 替换文档中的第一张图片
     *
     * @param inFilePath 文档地址路径
     * @param imgPath    新图片地址
     * @return 产生的新文件存放地址
     * @throws FileNotFoundException
     */
    public static String replaceOneImg(String inFilePath, String imgPath) throws FileNotFoundException {
        Document doc = new Document(inFilePath);
        SectionCollection sections = doc.getSections();
        boolean bool = false;
        for (int i = 0; i < sections.getCount(); i++) {
            if (bool) {
                break;
            }
            Section section = sections.get(i);
            ParagraphCollection paragraphs = section.getParagraphs();
            for (int j = 0; j < paragraphs.getCount(); j++) {
                if (bool) {
                    break;
                }
                DocumentObjectCollection childObjects = paragraphs.get(j).getChildObjects();
                for (int k = 0; k < childObjects.getCount(); k++) {
                    Object obj = childObjects.get(k);
                    if (obj instanceof DocPicture) {
                        DocPicture pic = (DocPicture) obj;
                        pic.loadImage(imgPath);
                        bool = true;
                        break;
                    }
                }
            }
        }
        String outFilePath = inFilePath.substring(0, inFilePath.lastIndexOf("."));
        outFilePath += "_副本.docx";
        doc.saveToFile(outFilePath, FileFormat.Docx);
        return outFilePath;
    }

    public static void main(String[] args) throws FileNotFoundException {
        String inFilePath = "C:\\Users\\DaiHaijiao\\Desktop/aaa.docx";
        String imgPath = "C:\\Users\\DaiHaijiao\\Pictures/gz.png";
        String outPath = WordUtils.replaceOneImg(inFilePath, imgPath);
        System.out.println(outPath);
    }

执行完后打开产生的新文件,如下图:

 可以看到,原先的那个假公章已经被替换了,由于代码中的main方法没有替换相应的标识内容,所有那些并没有被修改。代码中写的是替换第一张图片(具体根据自己业务适当变通一下)

2.3 替换文档中所有指定的相同文字成指定图片,替换前的模板如下图所示:

/**
     * 替换文档中所有指定的相同文字成指定图片
     *
     * @param inFilePath 文档地址路径
     * @param text       要替换的文字
     * @param imgPath    要替换成的图片路径
     * @return 产生的新文件存放地址
     * @throws FileNotFoundException
     */
    public static String replaceText2Img(String inFilePath, String text, String imgPath) throws FileNotFoundException {
        Document doc = new Document(inFilePath);

        TextSelection[] allString = doc.findAllString(text, true, false);
        int index;
        for (TextSelection textSelection : allString) {
            DocPicture pic = new DocPicture(doc);
            pic.loadImage(imgPath);
            TextRange range = textSelection.getAsOneRange();
            index = range.getOwnerParagraph().getChildObjects().indexOf(range);
            range.getOwnerParagraph().getChildObjects().insert(index, pic);
            range.getOwnerParagraph().getChildObjects().remove(range);
        }
        String outFilePath = inFilePath.substring(0, inFilePath.lastIndexOf("."));
        outFilePath += "_副本.docx";
        doc.saveToFile(outFilePath, FileFormat.Docx);
        return outFilePath;
    }

    public static void main(String[] args) throws FileNotFoundException {
        String inFilePath = "C:\\Users\\DaiHaijiao\\Desktop/aaa.docx";
        String imgPath = "C:\\Users\\DaiHaijiao\\Pictures/mf.png";
        String text = "${thisImg}";
        WordUtils.replaceText2Img(inFilePath, text, imgPath);
    }

 替换后如下:

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值