JAVA使用POI向doc加入图片

JAVA使用POI向doc加入图片

前言

刚来一个需求需要导出一个word文档,文档内是系统某个界面的各种数据图表,以图片的方式插入后导出。一番查阅资料于是乎着手开始编写简化demo,有关参考poi的文档查阅 Apache POI Word(docx) 入门示例教程

网上大多数是XXX模板占位然后插入图片,那种方式需要内置模板且图片需要转base64,并不是我想要的,我的需求很简单只要无脑插入导出即可。先上demo效果图。

注意:代码中宽高的单位一定要使用Units.toEMU(XXX)处理一下,否则就会出现插进去了但是你看不到效果的情况

在这里插入图片描述

依赖

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>

单元测试参考代码

在这里插入图片描述

@Slf4j
public class ImgDocTest {

    @Test
    void testExportDocContainsImg() throws IOException, InvalidFormatException {
        File dir = new File("D:\\tmp\\tmp\\20231208");
        File[] imagePaths = dir.listFiles();
        addImagesToWord(imagePaths);
    }

    private static void addImagesToWord(File[] imgs) throws IOException, InvalidFormatException {
        try (XWPFDocument document = new XWPFDocument()) {
            for (File img : imgs) {
                // 只对指定后缀的图片处理
                if (img.getName().endsWith("jpeg") || img.getName().endsWith("jpg") || img.getName().endsWith("png")) {
                    BufferedImage bufferedImage = ImageIO.read(img);
                    int imageType = XWPFDocument.PICTURE_TYPE_JPEG;
                    if (img.getName().endsWith(".png")) {
                        imageType = XWPFDocument.PICTURE_TYPE_PNG;
                    }

                    int width = bufferedImage.getWidth();
                    int height = bufferedImage.getHeight();

                    // Create a new run and add the image
                    XWPFRun run = document.createParagraph().createRun();
                    log.warn("fileName:{},height:{},width:{}", img.getName(), height, width);
                    run.addPicture(new FileInputStream(img), imageType, img.getName(), Units.toEMU(width), Units.toEMU(height));
                    // Optionally, you can add more text or formatting here

                    // Add a new line for the next image
                    document.createParagraph();
                } else {
                    continue;
                }

                // Save the modified document
                try (FileOutputStream fos = new FileOutputStream("D:\\tmp\\tmp\\20231208\\modify.doc")) {
                    document.write(fos);
                    System.out.println("Images added to Word document successfully.");
                }
            }
        }
    }
}

参考资料

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值