使用Java将图片添加到Excel的几种方式
1、超链接
使用POI,依赖如下
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency>
Java代码如下,运行该程序它会在桌面创建ImageLinks.xlsx文件。
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.*;import java.io.FileOutputStream;
import java.io.IOException;public class ExportTest {public static void main(String[] args) {// 创建工作簿XSSFWorkbook workbook = new XSSFWorkbook();XSSFSheet sheet = workbook.createSheet("Image Links");// 创建超链接XSSFRow row = sheet.createRow(0);XSSFCell cell = row.createCell(0);XSSFCreationHelper creationHelper = workbook.getCreationHelper();XSSFHyperlink hyperlink = creationHelper.createHyperlink(HyperlinkType.URL);hyperlink.setAddress("https://img1.baidu.com/it/u=727029913,321119353&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1698771600&t=fcf922a02fa5fc68ebf888e7fc1c9dcd");// 将超链接添加到单元格cell.setHyperlink(hyperlink);// 设置字体样式为蓝色XSSFFont font = workbook.createFont();font.setColor(IndexedColors.BLUE.getIndex());XSSFCellStyle style = workbook.createCellStyle();style.setFont(font);cell.setCellStyle(style);cell.setHyperlink(hyperlink);cell.setCellValue("点击这里下载图片");// 保存Excel文件到桌面String desktopPath = System.getProperty("user.home") + "/Desktop/";String filePath = desktopPath + "ImageLinks.xlsx";try (FileOutputStream outputStream = new FileOutputStream(filePath)) {workbook.write(outputStream);System.out.println("Excel file has been saved to the desktop.");} catch (IOException e) {e.printStackTrace();}}
}


点击它会自动打开浏览器访问设置的超链接

2、单元格插入图片 - POI
使用POI
下面是java代码
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.*;import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;public class ExportTest {public static void main(String[] args) {// 创建工作簿XSSFWorkbook workbook = new XSSFWorkbook();XSSFSheet sheet = workbook.createSheet("Images");// 从URL加载图片try {URL imageUrl = new URL("https://img1.baidu.com/it/u=727029913,321119353&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1698771600&t=fcf922a02fa5fc68ebf888e7fc1c9dcd");InputStream imageStream = imageUrl.openStream();byte[] bytes = IOUtils.toByteArray(imageStream);// 将图片插入到单元格XSSFRow row = sheet.createRow(0);XSSFCell cell = row.createCell(0);XSSFDrawing drawing = sheet.createDrawingPatriarch();XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, cell.getColumnIndex(), row.getRowNum(), cell.getColumnIndex() + 1, row.getRowNum() + 1);int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);XSSFPicture picture = drawing.createPicture(anchor, pictureIdx);picture.resize(); // 调整图片大小imageStream.close();} catch (IOException e) {e.printStackTrace();}// 保存Excel文件到桌面String desktopPath = System.getProperty("user.home") + "/Desktop/";String filePath = desktopPath + "ExcelWithImage.xlsx";try (FileOutputStream outputStream = new FileOutputStream(filePath)) {workbook.write(outputStream);System.out.println("Excel file with image has been saved to the desktop.");} catch (IOException e) {e.printStackTrace();}}
}
运行代码之后会在桌面生成文件ExcelWithImage.xlsx

可以看到图片插入到了单元格中

但是尺寸太大了并且占了n行n列,下面设置成占1行1列,只需要修改一行代码
// 设置固定尺寸picture.resize(1, 1);

看着还是有点别扭,再设置一下宽高,看下效果

可以看到已经非常Nice了,下面是调整后的代码
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.*;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;public class ExportTest {public static void main(String[] args) {// 创建工作簿XSSFWorkbook workbook = new XSSFWorkbook();XSSFSheet sheet = workbook.createSheet("Images");// 从URL加载图片try {URL imageUrl = new URL("https://img1.baidu.com/it/u=727029913,321119353&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1698771600&t=fcf922a02fa5fc68ebf888e7fc1c9dcd");InputStream imageStream = imageUrl.openStream();byte[] bytes = IOUtils.toByteArray(imageStream);// 将图片插入到单元格XSSFRow row = sheet.createRow(0);XSSFCell cell = row.createCell(0);// 设置单元格宽度,单位为字符int widthInCharacters = 10;row.getSheet().setColumnWidth(cell.getColumnIndex(), widthInCharacters * 256);// 设置单元格高度,单位为点数float heightInPoints = 100;row.setHeightInPoints(heightInPoints);XSSFDrawing drawing = sheet.createDrawingPatriarch();XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, cell.getColumnIndex(), row.getRowNum(), cell.getColumnIndex() + 1, row.getRowNum() + 1);int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);XSSFPicture picture = drawing.createPicture(anchor, pictureIdx);picture.resize(1, 1);// 调整图片大小imageStream.close();} catch (IOException e) {e.printStackTrace();}// 保存Excel文件到桌面String desktopPath = System.getProperty("user.home") + File.separator + "Desktop" + File.separator;String filePath = desktopPath + "ExcelWithImage.xlsx";try (FileOutputStream outputStream = new FileOutputStream(filePath)) {workbook.write(outputStream);System.out.println("Excel file with image has been saved to the desktop.");} catch (IOException e) {e.printStackTrace();}}
}
3、单元格插入图片 - EasyExcel
先看效果

代码如下:
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import org.apache.poi.util.IOUtils;import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;public class ExportTest {public static void main(String[] args) {try {// 从URL加载图片URL imageUrl = new URL("https://img1.baidu.com/it/u=727029913,321119353&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1698771600&t=fcf922a02fa5fc68ebf888e7fc1c9dcd");InputStream imageStream = imageUrl.openStream();byte[] bytes = IOUtils.toByteArray(imageStream);// 保存Excel文件到桌面String desktopPath = System.getProperty("user.home") + File.separator + "Desktop" + File.separator;String filePath = desktopPath + "ExcelWithImage.xlsx";// 使用EasyExcel创建ExcelEasyExcel.write(filePath).head(ImageData.class).sheet("Images").doWrite(data(bytes));System.out.println("Excel file with image has been saved to the desktop.");imageStream.close();} catch (IOException e) {e.printStackTrace();}}@ContentRowHeight(100)private static class ImageData {@ExcelProperty("图片")private byte[] imageBytes;public ImageData(byte[] imageBytes) {this.imageBytes = imageBytes;}public byte[] getImageBytes() {return imageBytes;}}private static List<ImageData> data(byte[] imageBytes) {List<ImageData> list = new ArrayList<>();list.add(new ImageData(imageBytes));return list;}
}相关文章:
使用Java将图片添加到Excel的几种方式
1、超链接 使用POI,依赖如下 <dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency>Java代码如下,运行该程序它会在桌面创建ImageLinks.xlsx文件。 …...
用什么台灯对眼睛最好?考公护眼台灯推荐
之前我一直觉得,孩子近视,是因为玩手机太多,看电子产品的时间过长,但后来控制孩子看电子产品时间的触底反弹与越来越深的度数告诉我,孩子近视的真正原因,我根本没有找到,后来看到一篇报告&#…...
【嵌入式开发 Linux 常用命令系列 4.2 -- .repo 各个目录介绍】
文章目录 概述.repo 目录结构manifests/default.xmlManifest 文件的作用default.xml 文件内容示例linkfile 介绍 .repo/projects 子目录配置和管理configHEADhooksinfo/excludeobjectsrr-cache 工作区中的对应目录 概述 repo 是一个由 Google 开发的版本控制工具,它…...
【C++学习手札】基于红黑树封装模拟实现map和set
🎬慕斯主页:修仙—别有洞天 💜本文前置知识: 红黑树 ♈️今日夜电波:漂流—菅原纱由理 2:55━━━━━━️💟──────── 4:29 …...
linux查看当前路径的所有文件大小;linux查看当前文件夹属于什么文件系统
1:指令查看当前路径所有文件内存空间大小;这样可以方便查询每个文件大小情况,根据需要进行删除 df -h // 根目录 du -ah --max-depth1 // 一级目录 虚拟机 du -ah -d 1 // 一级目录 设备使用 du -ah --max-depth2 // 二…...
PPT插件-好用的插件-超级文本-大珩助手
常用字体 内置了大量的常用字体,方便快捷的一键更换字体,避免系统字体过多卡顿 文字整理 包含删空白行、清理编号、清理格式,便于处理从网络上复制的资料 文本打散与合并 包含文本打散、文本合并,文本打散可实现将一个文本打散…...
Kafka中的Topic
在Kafka中,Topic是消息的逻辑容器,用于组织和分类消息。本文将深入探讨Kafka Topic的各个方面,包括创建、配置、生产者和消费者,以及一些实际应用中的示例代码。 1. 介绍 在Kafka中,Topic是消息的逻辑通道࿰…...
LAMP部署
目录 一、安装apache 二、配置mysql 三、安装php 四、搭建论坛 4、安装另一个网站 一、安装apache 1.关闭防火墙,将安装Apache所需软件包传到/opt目录下 systemctl stop firewalld systemctl disable firewalld setenforce 0 httpd-2.4.29.tar.gz apr-1.6.2.t…...
DouyinAPI接口开发系列丨商品详情数据丨视频详情数据
电商API就是各大电商平台提供给开发者访问平台数据的接口。目前,主流电商平台如淘宝、天猫、京东、苏宁等都有自己的API。 二、电商API的应用价值 1.直接对接原始数据源,数据提取更加准确和完整。 2.查询速度更快,可以快速响应用户请求实现…...
AWS Remote Control ( Wi-Fi ) on i.MX RT1060 EVK - 3 “编译 NXP i.MX RT1060”( 完 )
此章节叙述如何修改、建构 i.MX RT1060 的 Sample Code“aws_remote_control_wifi_nxp” 1. 点击“Import SDK example(s)” 2. 选择“MIMXRT1062xxxxA”>“evkmimxrt1060”,并确认 SDK 版本后,点击“Next>” 3. 选择“aws_examples”>“aw…...
5G - NR物理层解决方案支持6G非地面网络中的高移动性
文章目录 非地面网络场景链路仿真参数实验仿真结果 非地面网络场景 链路仿真参数 实验仿真结果 Figure 5 && Figure 6:不同信噪比下的BER和吞吐量 变量 SISO 2x2MIMO 2x4MIMO 2x8MIMOReyleigh衰落、Rician衰落、多径TDL-A(NLOS) 、TDL-E(LOS)(a)QPSK (b)16…...
python epub文件解析
python epub文件解析 代码BeautifulSoup 介绍解释 代码 import ebooklib from bs4 import BeautifulSoup from ebooklib import epubbook epub.read_epub("逻辑思维训练1200题.epub")# 解析 for item in book.get_items():# 提取书中的文本内容if item.get_type() …...
Visual Studio 2015 中 FFmpeg 开发环境的搭建
Visual Studio 2015 中 FFmpeg 开发环境的搭建 Visual Studio 2015 中 FFmpeg 开发环境的搭建新建控制台工程拷贝并配置 FFmpeg 开发文件测试FFmpeg 开发文件的下载链接 Visual Studio 2015 中 FFmpeg 开发环境的搭建 新建控制台工程 新建 Win32 控制台应用程序。 具体流程&…...
期末速成数据库极简版【存储过程】(5)
目录 【7】系统存储过程 【8】用户存储过程——带输出参数的存储过程 创建存储过程 存储过程调用 【9】用户存储过程——不带输出参数的存储过程 【7】系统存储过程 系统存储我们就不做过程讲解用户存储过程会考察一道大题,所以我们把重点放在用户存储过程。…...
Android Studio的代码笔记--IntentService学习
IntentService学习 IntentService常规用法清单注册服务服务内容开启服务 IntentService 一个 HandlerThread工作线程,通过Handler实现把消息加入消息队列中等待执行,通过传递的intent在onHandleIntent中处理任务。(多次调用会按顺序执行事件…...
C语言 - 字符函数和字符串函数
系列文章目录 文章目录 系列文章目录前言1. 字符分类函数islower 是能够判断参数部分的 c 是否是⼩写字⺟的。 通过返回值来说明是否是⼩写字⺟,如果是⼩写字⺟就返回⾮0的整数,如果不是⼩写字⺟,则返回0。 2. 字符转换函数3. strlen的使⽤和…...
Redis rdb源码解析
前置学习:Redis server启动源码-CSDN博客 1、触发时机 1、执行save命令--->rdbSave函数 2、执行bgsave命令--->rdbSaveBackground函数或者(serverCron->prepareForShutdown) 3,主从复制-->startBgsaveForReplication…...
深入理解CyclicBarrier
文章目录 1. 概念2. CylicBarier使用简单案例3. 源码 1. 概念 CyclicBarrier 字面意思回环栅栏(循环屏障),通过它可以实现让一组线程等待至某个状态(屏障点)之后再全部同时执行。叫做回环是因为当所有等待线程都被释放…...
微信小程序 - 格式化操作 moment.js格式化常用使用方法总结大全
格式化操作使用 1. 首先,下载一个第三方库 moment npm i moment --save 注:在微信小程序中无法直接npm 下载 导入 的(安装一个就需要构建一次) 解决:菜单栏 --> 工具 --> 构建 npm 点击即可(会…...
学习pytorch18 pytorch完整的模型训练流程
pytorch完整的模型训练流程 1. 流程1. 整理训练数据 使用CIFAR10数据集2. 搭建网络结构3. 构建损失函数4. 使用优化器5. 训练模型6. 测试数据 计算模型预测正确率7. 保存模型 2. 代码1. model.py2. train.py 3. 结果tensorboard结果以下图片 颜色较浅的线是真实计算的值&#x…...
模型参数、模型存储精度、参数与显存
模型参数量衡量单位 M:百万(Million) B:十亿(Billion) 1 B 1000 M 1B 1000M 1B1000M 参数存储精度 模型参数是固定的,但是一个参数所表示多少字节不一定,需要看这个参数以什么…...
《Playwright:微软的自动化测试工具详解》
Playwright 简介:声明内容来自网络,将内容拼接整理出来的文档 Playwright 是微软开发的自动化测试工具,支持 Chrome、Firefox、Safari 等主流浏览器,提供多语言 API(Python、JavaScript、Java、.NET)。它的特点包括&a…...
ServerTrust 并非唯一
NSURLAuthenticationMethodServerTrust 只是 authenticationMethod 的冰山一角 要理解 NSURLAuthenticationMethodServerTrust, 首先要明白它只是 authenticationMethod 的选项之一, 并非唯一 1 先厘清概念 点说明authenticationMethodURLAuthenticationChallenge.protectionS…...
基于Docker Compose部署Java微服务项目
一. 创建根项目 根项目(父项目)主要用于依赖管理 一些需要注意的点: 打包方式需要为 pom<modules>里需要注册子模块不要引入maven的打包插件,否则打包时会出问题 <?xml version"1.0" encoding"UTF-8…...
uniapp微信小程序视频实时流+pc端预览方案
方案类型技术实现是否免费优点缺点适用场景延迟范围开发复杂度WebSocket图片帧定时拍照Base64传输✅ 完全免费无需服务器 纯前端实现高延迟高流量 帧率极低个人demo测试 超低频监控500ms-2s⭐⭐RTMP推流TRTC/即构SDK推流❌ 付费方案 (部分有免费额度&#x…...
uniapp中使用aixos 报错
问题: 在uniapp中使用aixos,运行后报如下错误: AxiosError: There is no suitable adapter to dispatch the request since : - adapter xhr is not supported by the environment - adapter http is not available in the build 解决方案&…...
大数据学习(132)-HIve数据分析
🍋🍋大数据学习🍋🍋 🔥系列专栏: 👑哲学语录: 用力所能及,改变世界。 💖如果觉得博主的文章还不错的话,请点赞👍收藏⭐️留言Ǵ…...
智能分布式爬虫的数据处理流水线优化:基于深度强化学习的数据质量控制
在数字化浪潮席卷全球的今天,数据已成为企业和研究机构的核心资产。智能分布式爬虫作为高效的数据采集工具,在大规模数据获取中发挥着关键作用。然而,传统的数据处理流水线在面对复杂多变的网络环境和海量异构数据时,常出现数据质…...
【Java学习笔记】BigInteger 和 BigDecimal 类
BigInteger 和 BigDecimal 类 二者共有的常见方法 方法功能add加subtract减multiply乘divide除 注意点:传参类型必须是类对象 一、BigInteger 1. 作用:适合保存比较大的整型数 2. 使用说明 创建BigInteger对象 传入字符串 3. 代码示例 import j…...
管理学院权限管理系统开发总结
文章目录 🎓 管理学院权限管理系统开发总结 - 现代化Web应用实践之路📝 项目概述🏗️ 技术架构设计后端技术栈前端技术栈 💡 核心功能特性1. 用户管理模块2. 权限管理系统3. 统计报表功能4. 用户体验优化 🗄️ 数据库设…...
