java 用word模板打标签,并插入图片 动态生成word

代码 word模板及生成word下载

下载地址

先制作word模板

在这里插入图片描述

比如说这个模板。首先对模板给于占位,我为了方便用代码获取,前面加了$,这都随意,在标号占位后

一定记得 例如$name选中右键复制->粘贴只保留文本(有时候打码读取时会有占位符)

最后记得word另存为docx文件

在这里插入图片描述

pom加 jar

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-excelant</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.0.0</version>
        </dependency>
        <!-- 生成图片-->
        <dependency>
            <groupId>org.jfree</groupId>
            <artifactId>jfreechart</artifactId>
            <version>1.0.19</version>
        </dependency>
        <dependency>
            <!--支持插入图片-->
            <groupId>org.docx4j</groupId>
            <artifactId>docx4j</artifactId>
            <version>3.3.1</version>
        </dependency>

制作好模板后 核心代码

/**
     * 将word中某些标签替换成指定的值,并生成一个新的word文档。
     *
     * @param templateFilePath word模板文件路径
     * @param outFilePath      填充后输出文件路径
     * @param map              key:word中的占位标签,value对应标签要替换的值。
     * @throws IOException
     */
    public static void insertAndOutFile(String templateFilePath, String outFilePath, Map<String, String> map) throws IOException, InvalidFormatException {
        //准备工作,生成docx对象
        String templatePath = templateFilePath;
        InputStream is = new FileInputStream(templatePath);
        XWPFDocument docx = new XWPFDocument(is);
        //获取段落
        List<XWPFParagraph> paras = docx.getParagraphs();
        for (XWPFParagraph para : paras) {
            for (XWPFRun run : para.getRuns()) {
                //遍历该段里的所有文本
                String str = run.toString().trim();
                System.out.println(str);
                //如果该段文本包含map中的key,则替换为map中的value值。
                Set<String> keySet = map.keySet();
                for (String key : keySet) {
                    if (str.trim().equals(key)) {
                        System.out.println("key" + map.get(key));
                        //替换该文本0位置的数据。
                        run.setText(map.get(key), 0);
                    }
                }
            }
        }
        //获取表格
        List<XWPFTable> tables = docx.getTables();
        //定位到第一个表格
        XWPFTable table = tables.get(0);
        //遍历该表格所有的行
        for (int i = 0; i < table.getRows().size(); i++) {
            XWPFTableRow row = table.getRow(i);
            //遍历该行所有的列
            for (int j = 0; j < row.getTableCells().size(); j++) {
                XWPFTableCell cell = row.getTableCells().get(j);
                //获取该格子里所有的段
                List<XWPFParagraph> paragraphs = cell.getParagraphs();
                for (XWPFParagraph p : paragraphs) {
                    //遍历该格子里的段
                    List<XWPFRun> runs = p.getRuns();
                    for (XWPFRun run : runs) {
                        //遍历该段里的所有文本
                        String str = run.toString().trim();
                        System.out.println(str);
                        //如果该段文本包含map中的key,则替换为map中的value值。
                        Set<String> keySet = map.keySet();
                        for (String key : keySet) {
                            if (str.trim().equals(key)) {
                                if (key.contains("$img")) {
                                    System.out.println("key" + map.get(key));
                                    if (StrKit.notBlank(map.get(key)) && key.equals(str.trim())) {
                                        //获取本地图片
                                        run.addPicture(new FileInputStream(map.get(key)),
                                                XWPFDocument.PICTURE_TYPE_PNG,
                                                str+".png",
                                                Units.toEMU(300),
                                                Units.toEMU(150)
                                        );
                                        run.setText("", 0);//删除
                                    } else {
                                        run.setText("", 0);
                                    }
                                }
                                else {
                                    System.out.println("key" + map.get(key));
                                    //替换该文本0位置的数据。
                                    run.setText(map.get(key), 0);
                                }
                            }
                        }
                    }
                }
            }
        }
        //输出
        OutputStream os = new FileOutputStream(outFilePath);
        docx.write(os);
        is.close();
        os.close();

    }


    public static void main(String[] args) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("$name", "名字");
        map.put("$serial_number", "编号");
        map.put("$department", "部门");
        map.put("$reason_text", "事由");
        map.put("$notice_content_text", "内容");
        map.put("$requirement_content_text", "要求");
        map.put("$img1", "D://1.png");
        map.put("$img2", "D://1.png");
        map.put("$img3", "D://1.png");
        map.put("$img4", "D://1.png");
        map.put("$img5", "");
        map.put("$submit", "1215456464");
        map.put("$submit_date", "2022-01-02");
        insertAndOutFile("D:\\test1.docx", "D:\\out.docx", map);
    }

生成后word
在这里插入图片描述

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Java中,可以使用Apache POI库来生成Word文档并插入表格和图片。下面是一个简单的示例代码: 首先,需要引入Apache POI库的依赖: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 然后,可以使用以下代码生成一个Word文件并插入表格和图片: ```java import org.apache.poi.util.IOUtils; import org.apache.poi.xwpf.usermodel.*; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; public class WordGenerator { public static void main(String[] args) { try { // 创建一个新的Word文档 XWPFDocument document = new XWPFDocument(); // 创建一个表格 XWPFTable table = document.createTable(3, 3); // 往表格中添加内容 table.getRow(0).getCell(0).setText("姓名"); table.getRow(0).getCell(1).setText("性别"); table.getRow(0).getCell(2).setText("年龄"); table.getRow(1).getCell(0).setText("张三"); table.getRow(1).getCell(1).setText("男"); table.getRow(1).getCell(2).setText("20"); table.getRow(2).getCell(0).setText("李四"); table.getRow(2).getCell(1).setText("女"); table.getRow(2).getCell(2).setText("22"); // 插入一张图片 InputStream imageStream = new FileInputStream("path/to/image.jpg"); XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); run.addPicture(imageStream, XWPFDocument.PICTURE_TYPE_JPEG, "image.jpg", Units.toEMU(200), Units.toEMU(200)); imageStream.close(); // 保存Word文档 FileOutputStream out = new FileOutputStream("path/to/output.docx"); document.write(out); out.close(); System.out.println("Word文档生成成功!"); } catch (Exception e) { e.printStackTrace(); } } } ``` 需要注意的是,上述代码中的图片路径和输出路径需要根据实际情况修改。另外,还需要根据实际需求来调整表格的行数、列数以及单元格内容。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值