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

使用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&#xff0c;依赖如下 <dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency>Java代码如下,运行该程序它会在桌面创建ImageLinks.xlsx文件。 …...

用什么台灯对眼睛最好?考公护眼台灯推荐

之前我一直觉得&#xff0c;孩子近视&#xff0c;是因为玩手机太多&#xff0c;看电子产品的时间过长&#xff0c;但后来控制孩子看电子产品时间的触底反弹与越来越深的度数告诉我&#xff0c;孩子近视的真正原因&#xff0c;我根本没有找到&#xff0c;后来看到一篇报告&#…...

【嵌入式开发 Linux 常用命令系列 4.2 -- .repo 各个目录介绍】

文章目录 概述.repo 目录结构manifests/default.xmlManifest 文件的作用default.xml 文件内容示例linkfile 介绍 .repo/projects 子目录配置和管理configHEADhooksinfo/excludeobjectsrr-cache 工作区中的对应目录 概述 repo 是一个由 Google 开发的版本控制工具&#xff0c;它…...

【C++学习手札】基于红黑树封装模拟实现map和set

​ &#x1f3ac;慕斯主页&#xff1a;修仙—别有洞天 &#x1f49c;本文前置知识&#xff1a; 红黑树 ♈️今日夜电波&#xff1a;漂流—菅原纱由理 2:55━━━━━━️&#x1f49f;──────── 4:29 …...

linux查看当前路径的所有文件大小;linux查看当前文件夹属于什么文件系统

1&#xff1a;指令查看当前路径所有文件内存空间大小&#xff1b;这样可以方便查询每个文件大小情况&#xff0c;根据需要进行删除 df -h // 根目录 du -ah --max-depth1 // 一级目录 虚拟机 du -ah -d 1 // 一级目录 设备使用 du -ah --max-depth2 // 二…...

PPT插件-好用的插件-超级文本-大珩助手

常用字体 内置了大量的常用字体&#xff0c;方便快捷的一键更换字体&#xff0c;避免系统字体过多卡顿 文字整理 包含删空白行、清理编号、清理格式&#xff0c;便于处理从网络上复制的资料 文本打散与合并 包含文本打散、文本合并&#xff0c;文本打散可实现将一个文本打散…...

Kafka中的Topic

在Kafka中&#xff0c;Topic是消息的逻辑容器&#xff0c;用于组织和分类消息。本文将深入探讨Kafka Topic的各个方面&#xff0c;包括创建、配置、生产者和消费者&#xff0c;以及一些实际应用中的示例代码。 1. 介绍 在Kafka中&#xff0c;Topic是消息的逻辑通道&#xff0…...

LAMP部署

目录 一、安装apache 二、配置mysql 三、安装php 四、搭建论坛 4、安装另一个网站 一、安装apache 1.关闭防火墙&#xff0c;将安装Apache所需软件包传到/opt目录下 systemctl stop firewalld systemctl disable firewalld setenforce 0 httpd-2.4.29.tar.gz apr-1.6.2.t…...

DouyinAPI接口开发系列丨商品详情数据丨视频详情数据

电商API就是各大电商平台提供给开发者访问平台数据的接口。目前&#xff0c;主流电商平台如淘宝、天猫、京东、苏宁等都有自己的API。 二、电商API的应用价值 1.直接对接原始数据源&#xff0c;数据提取更加准确和完整。 2.查询速度更快&#xff0c;可以快速响应用户请求实现…...

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”&#xff0c;并确认 SDK 版本后&#xff0c;点击“Next>” 3. 选择“aws_examples”>“aw…...

5G - NR物理层解决方案支持6G非地面网络中的高移动性

文章目录 非地面网络场景链路仿真参数实验仿真结果 非地面网络场景 链路仿真参数 实验仿真结果 Figure 5 && Figure 6&#xff1a;不同信噪比下的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】系统存储过程 系统存储我们就不做过程讲解用户存储过程会考察一道大题&#xff0c;所以我们把重点放在用户存储过程。…...

Android Studio的代码笔记--IntentService学习

IntentService学习 IntentService常规用法清单注册服务服务内容开启服务 IntentService 一个 HandlerThread工作线程&#xff0c;通过Handler实现把消息加入消息队列中等待执行&#xff0c;通过传递的intent在onHandleIntent中处理任务。&#xff08;多次调用会按顺序执行事件…...

C语言 - 字符函数和字符串函数

系列文章目录 文章目录 系列文章目录前言1. 字符分类函数islower 是能够判断参数部分的 c 是否是⼩写字⺟的。 通过返回值来说明是否是⼩写字⺟&#xff0c;如果是⼩写字⺟就返回⾮0的整数&#xff0c;如果不是⼩写字⺟&#xff0c;则返回0。 2. 字符转换函数3. strlen的使⽤和…...

Redis rdb源码解析

前置学习&#xff1a;Redis server启动源码-CSDN博客 1、触发时机 1、执行save命令--->rdbSave函数 2、执行bgsave命令--->rdbSaveBackground函数或者&#xff08;serverCron->prepareForShutdown&#xff09; 3&#xff0c;主从复制-->startBgsaveForReplication…...

深入理解CyclicBarrier

文章目录 1. 概念2. CylicBarier使用简单案例3. 源码 1. 概念 CyclicBarrier 字面意思回环栅栏&#xff08;循环屏障&#xff09;&#xff0c;通过它可以实现让一组线程等待至某个状态&#xff08;屏障点&#xff09;之后再全部同时执行。叫做回环是因为当所有等待线程都被释放…...

微信小程序 - 格式化操作 moment.js格式化常用使用方法总结大全

格式化操作使用 1. 首先&#xff0c;下载一个第三方库 moment npm i moment --save 注&#xff1a;在微信小程序中无法直接npm 下载 导入 的&#xff08;安装一个就需要构建一次&#xff09; 解决&#xff1a;菜单栏 --> 工具 --> 构建 npm 点击即可&#xff08;会…...

学习pytorch18 pytorch完整的模型训练流程

pytorch完整的模型训练流程 1. 流程1. 整理训练数据 使用CIFAR10数据集2. 搭建网络结构3. 构建损失函数4. 使用优化器5. 训练模型6. 测试数据 计算模型预测正确率7. 保存模型 2. 代码1. model.py2. train.py 3. 结果tensorboard结果以下图片 颜色较浅的线是真实计算的值&#x…...

基于算法竞赛的c++编程(28)结构体的进阶应用

结构体的嵌套与复杂数据组织 在C中&#xff0c;结构体可以嵌套使用&#xff0c;形成更复杂的数据结构。例如&#xff0c;可以通过嵌套结构体描述多层级数据关系&#xff1a; struct Address {string city;string street;int zipCode; };struct Employee {string name;int id;…...

【SpringBoot】100、SpringBoot中使用自定义注解+AOP实现参数自动解密

在实际项目中,用户注册、登录、修改密码等操作,都涉及到参数传输安全问题。所以我们需要在前端对账户、密码等敏感信息加密传输,在后端接收到数据后能自动解密。 1、引入依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId...

ServerTrust 并非唯一

NSURLAuthenticationMethodServerTrust 只是 authenticationMethod 的冰山一角 要理解 NSURLAuthenticationMethodServerTrust, 首先要明白它只是 authenticationMethod 的选项之一, 并非唯一 1 先厘清概念 点说明authenticationMethodURLAuthenticationChallenge.protectionS…...

大学生职业发展与就业创业指导教学评价

这里是引用 作为软工2203/2204班的学生&#xff0c;我们非常感谢您在《大学生职业发展与就业创业指导》课程中的悉心教导。这门课程对我们即将面临实习和就业的工科学生来说至关重要&#xff0c;而您认真负责的教学态度&#xff0c;让课程的每一部分都充满了实用价值。 尤其让我…...

Linux 中如何提取压缩文件 ?

Linux 是一种流行的开源操作系统&#xff0c;它提供了许多工具来管理、压缩和解压缩文件。压缩文件有助于节省存储空间&#xff0c;使数据传输更快。本指南将向您展示如何在 Linux 中提取不同类型的压缩文件。 1. Unpacking ZIP Files ZIP 文件是非常常见的&#xff0c;要在 …...

轻量级Docker管理工具Docker Switchboard

简介 什么是 Docker Switchboard &#xff1f; Docker Switchboard 是一个轻量级的 Web 应用程序&#xff0c;用于管理 Docker 容器。它提供了一个干净、用户友好的界面来启动、停止和监控主机上运行的容器&#xff0c;使其成为本地开发、家庭实验室或小型服务器设置的理想选择…...

大数据驱动企业决策智能化的路径与实践

&#x1f4dd;个人主页&#x1f339;&#xff1a;慌ZHANG-CSDN博客 &#x1f339;&#x1f339;期待您的关注 &#x1f339;&#x1f339; 一、引言&#xff1a;数据驱动的企业竞争力重构 在这个瞬息万变的商业时代&#xff0c;“快者胜”的竞争逻辑愈发明显。企业如何在复杂环…...

Spring AI中使用ChatMemory实现会话记忆功能

文章目录 1、需求2、ChatMemory中消息的存储位置3、实现步骤1、引入依赖2、配置Spring AI3、配置chatmemory4、java层传递conversaionId 4、验证5、完整代码6、参考文档 1、需求 我们知道大型语言模型 &#xff08;LLM&#xff09; 是无状态的&#xff0c;这就意味着他们不会保…...

【QT】qtdesigner中将控件提升为自定义控件后,css设置样式不生效(已解决,图文详情)

目录 0.背景 1.解决思路 2.详细代码 0.背景 实际项目中遇到的问题&#xff0c;描述如下&#xff1a; 我在qtdesigner用界面拖了一个QTableView控件&#xff0c;object name为【tableView_electrode】&#xff0c;然后【提升为】了自定义的类【Steer_Electrode_Table】&…...

华为云Flexus+DeepSeek征文|华为云Flexus服务器dify平台通过自然语言转sql并执行实现电商数据分析

目录 前言 1 华为云Flexus服务器部署Dify平台 1.1 华为云Flexus服务器一键部署Dify平台 1.2 设置账号登录Dify&#xff0c;进入平台 2 构建自然语言转SQL并执行的应用 2.1 创建应用并启动工作流设计 2.2 应用框架设计 2.3 自然语言转SQL模块详解 2.4 代码执行模块实现…...