使用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…...
23-Oracle 23 ai 区块链表(Blockchain Table)
小伙伴有没有在金融强合规的领域中遇见,必须要保持数据不可变,管理员都无法修改和留痕的要求。比如医疗的电子病历中,影像检查检验结果不可篡改行的,药品追溯过程中数据只可插入无法删除的特性需求;登录日志、修改日志…...
【位运算】消失的两个数字(hard)
消失的两个数字(hard) 题⽬描述:解法(位运算):Java 算法代码:更简便代码 题⽬链接:⾯试题 17.19. 消失的两个数字 题⽬描述: 给定⼀个数组,包含从 1 到 N 所有…...
如何为服务器生成TLS证书
TLS(Transport Layer Security)证书是确保网络通信安全的重要手段,它通过加密技术保护传输的数据不被窃听和篡改。在服务器上配置TLS证书,可以使用户通过HTTPS协议安全地访问您的网站。本文将详细介绍如何在服务器上生成一个TLS证…...
工业自动化时代的精准装配革新:迁移科技3D视觉系统如何重塑机器人定位装配
AI3D视觉的工业赋能者 迁移科技成立于2017年,作为行业领先的3D工业相机及视觉系统供应商,累计完成数亿元融资。其核心技术覆盖硬件设计、算法优化及软件集成,通过稳定、易用、高回报的AI3D视觉系统,为汽车、新能源、金属制造等行…...
rnn判断string中第一次出现a的下标
# coding:utf8 import torch import torch.nn as nn import numpy as np import random import json""" 基于pytorch的网络编写 实现一个RNN网络完成多分类任务 判断字符 a 第一次出现在字符串中的位置 """class TorchModel(nn.Module):def __in…...
保姆级教程:在无网络无显卡的Windows电脑的vscode本地部署deepseek
文章目录 1 前言2 部署流程2.1 准备工作2.2 Ollama2.2.1 使用有网络的电脑下载Ollama2.2.2 安装Ollama(有网络的电脑)2.2.3 安装Ollama(无网络的电脑)2.2.4 安装验证2.2.5 修改大模型安装位置2.2.6 下载Deepseek模型 2.3 将deepse…...
华为OD机考-机房布局
import java.util.*;public class DemoTest5 {public static void main(String[] args) {Scanner in new Scanner(System.in);// 注意 hasNext 和 hasNextLine 的区别while (in.hasNextLine()) { // 注意 while 处理多个 caseSystem.out.println(solve(in.nextLine()));}}priv…...
iview框架主题色的应用
1.下载 less要使用3.0.0以下的版本 npm install less2.7.3 npm install less-loader4.0.52./src/config/theme.js文件 module.exports {yellow: {theme-color: #FDCE04},blue: {theme-color: #547CE7} }在sass中使用theme配置的颜色主题,无需引入,直接可…...
TSN交换机正在重构工业网络,PROFINET和EtherCAT会被取代吗?
在工业自动化持续演进的今天,通信网络的角色正变得愈发关键。 2025年6月6日,为期三天的华南国际工业博览会在深圳国际会展中心(宝安)圆满落幕。作为国内工业通信领域的技术型企业,光路科技(Fiberroad&…...
Scrapy-Redis分布式爬虫架构的可扩展性与容错性增强:基于微服务与容器化的解决方案
在大数据时代,海量数据的采集与处理成为企业和研究机构获取信息的关键环节。Scrapy-Redis作为一种经典的分布式爬虫架构,在处理大规模数据抓取任务时展现出强大的能力。然而,随着业务规模的不断扩大和数据抓取需求的日益复杂,传统…...
