当前位置: 首页 > news >正文

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 {@Testvoid 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 imageXWPFRun 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 imagedocument.createParagraph();} else {continue;}// Save the modified documenttry (FileOutputStream fos = new FileOutputStream("D:\\tmp\\tmp\\20231208\\modify.doc")) {document.write(fos);System.out.println("Images added to Word document successfully.");}}}}
}

参考资料

  • Apache POI Word(docx) 入门示例教程
  • 插入图片显示不了的问题
http://www.lryc.cn/news/255564.html

相关文章:

  • 反向传播算法
  • 记录 | ubuntu降低内核版本的方法
  • MX6ULL学习笔记 (八) platform 设备驱动实验
  • 初识Linux:权限(2)
  • 测试环境使用问题及其优化对策实践
  • 【力扣】206.反转链表
  • Python:核心知识点整理大全7-笔记
  • Hadoop学习笔记(HDP)-Part.15 安装HIVE
  • 【力扣100】4.移动零
  • Filebeat使用指南
  • 【Vue2】Vue的介绍与Vue的第一个实例
  • 十五届蓝桥杯分享会(一)
  • 原生video设置控制面板controls显示哪些控件
  • openlayers地图使用---跟随地图比例尺动态标绘大小的一种方式2
  • C语言期末考试复习PTA数据类型及表达式-分支结构程序-循环结构-数组经典选择题
  • RHEL8_Linux访问NFS存储及自动挂载
  • python 使用 AppiumService 类启动appium server
  • HbuilderX使用Uniapp+Vue3安装uview-plus
  • 【Android】Java NIO(New I/O)的`Selector`类来实现非阻塞的Socket监听
  • 『亚马逊云科技产品测评』在当前飞速发展的AI人工智能时代云服务技术哪家强?
  • 经典神经网络——ResNet模型论文详解及代码复现
  • OpenCV-Python:DevCloud CodeLab介绍及学习
  • 如何在Linux环境搭建本地SVN服务器并结合cpolar实现公网访问
  • C语言入门课程之课后习题之折半查找法
  • 【CSP】202209-1_如此编码Python实现
  • std::function
  • SQL Server——权限管理
  • 实例解析关于兔鲜登录tab栏切换案例详细讲解!
  • 制作一个RISC-V的操作系统三-编译与链接
  • tmux工具--程序部署在服务器上持久化执行