使用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创建Excel
            EasyExcel.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;
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/239433.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【从零开始学习JVM | 第六篇】快速了解 直接内存

前言&#xff1a; 当谈及Java虚拟机&#xff08;JVM&#xff09;的内存管理时&#xff0c;我们通常会想到堆内存和栈内存。然而&#xff0c;还有一种被称为"直接内存"的特殊内存区域&#xff0c;它在Java应用程序中起着重要的作用。直接内存提供了一种与Java堆内存和…

十几个软件测试实战项目【外卖/医药/银行/电商/金融】

项目一&#xff1a;ShopNC商城 项目概况&#xff1a; ShopNC商城是一个电子商务B2C电商平台系统&#xff0c;功能强大&#xff0c;安全便捷。适合企业及个人快速构建个性化网上商城。 包含PCIOS客户端Adroid客户端微商城&#xff0c;系统PC后台是基于ThinkPHP MVC构架开发的跨…

windows如何解决端口冲突(实用篇)

在项目设计中&#xff0c;环境配置成功点击运行瞬间&#xff0c;一大堆红爆出&#xff0c;8080端口占用&#xff0c;这个是很烦人的。。。 解决方式&#xff1a; 笨方法&#xff1a;一、查看所有端口实用情况&#xff08;挨个扫&#xff09; 按住【WINR】快捷键打开运行输入…

Android View闪烁动画AlphaAnimation,Kotlin

Android View闪烁动画AlphaAnimation&#xff0c;Kotlin private fun flickerAnimation(view: View?) {val animation: Animation AlphaAnimation(1f, 0f) //不透明到透明。animation.duration 500 // 1次过程时长。animation.interpolator LinearInterpolator() // 线性速…

赴美上市传闻再起,SHEIN走到十字路口

作者 | 辰纹 来源 | 洞见新研社 裹挟着“黑五”大胜的余波&#xff0c;跨境电商巨头SHEIN&#xff08;希音&#xff09;将赴美IPO的传闻又在行业中散播开来。 金融投资报称SHEIN此次IPO的估值或达900亿美元&#xff1b;上海证券报表示&#xff0c;SHEIN已对投资人发出了路演…

10天玩转Python第3天:python循环语句和字符串、列表全面详解与代码示例

目录 1 循环1.1 for 循环1.2 break 和 continue 2 容器3 字符串3.1 定义3.2 下标3.3 切片3.4 字符串的查找方法 find3.5 字符串的替换方法 replace3.6 字符串的拆分 split3.7 字符串的链接 join 4 列表4.1 定义4.1 列表支持下标和切片, 长度4.3 查找 - 查找列表中数据下标的方法…

centos7x 安装支持gpu驱动的docker

1、卸载以前版本的驱动 sudo /usr/bin/nvidia-uninstall2、先安装基础项 yum install kernel kernel-devel gcc make -yyum install kernel kernel-devel gcc gcc-c make -y 3、禁用驱动源 nouveau echo "blacklist nouveau " >>/etc/modp…

12.12_黑马数据结构与算法笔记Java

目录 079 优先级队列 无序数组实现 080 优先级队列 有序数组实现 081 优先级队列 堆实现 1 082 优先级队列 堆实现 2 083 优先级队列 堆实现 3 084 优先级队列 e01 合并多个有序链表1 084 优先级队列 e01 合并多个有序链表2 085 阻塞队列 问题提出 086 阻塞队列 单锁实…

Linux:gdb的简单使用

个人主页 &#xff1a; 个人主页 个人专栏 &#xff1a; 《数据结构》 《C语言》《C》《Linux》 文章目录 前言一、前置理解二、使用总结 前言 gdb是Linux中的调试代码的工具 一、前置理解 我们都知道要调试一份代码&#xff0c;这份代码的发布模式必须是debug。那你知道在li…

【代码随想录】刷题笔记Day34

前言 考过概率论&#xff0c;发过一场烧&#xff0c;兜兜转转又一月&#xff0c;轻舟已撞万重山&#xff0c;赶紧刷题 贪心算法理论基础 贪心的本质&#xff1a;局部最优→全局最优无套路&#xff0c;常识性推导 举反例 455. 分发饼干 - 力扣&#xff08;LeetCode&#xf…

FastAPI之响应模型

前言 响应模型我认为最主要的作用就是在自动化文档的显示时&#xff0c;可以直接给查看文档的小伙伴显示返回的数据格式。对于后端开发的伙伴来说&#xff0c;其编码的实际意义不大&#xff0c;但是为了可以不用再额外的提供文档&#xff0c;我们只需要添加一个 response_mod…

慢SQL诊断

最近经常遇到技术开发跑来问我慢SQL优化相关工作&#xff0c;所以干脆出几篇SQL相关优化技术月报&#xff0c;我这里就以公司mysql一致的5.7版本来说明下。 在企业中慢SQL问题进场会遇到&#xff0c;尤其像我们这种ERP行业。 成熟的公司企业都会有晚上的慢SQL监控和预警机制。…

784. 字母大小写全排列

字母大小写全排列 描述 : 给定一个字符串 s &#xff0c;通过将字符串 s 中的每个字母转变大小写&#xff0c;我们可以获得一个新的字符串。 返回 所有可能得到的字符串集合 。以 任意顺序 返回输出。 回文串 是正着读和反着读都一样的字符串。 题目 : LeetCode 784. 字母…

Linux--操作系统

1. 常见的操作系统 Windowsmac OSLinuxiOSAndroid 2. 操作系统的定义 操作系统直接运行在计算机上的系统软件&#xff0c; 它是控制硬件和支持软件运行的计算机程序。 3. 操作系统的作用 向下控制硬件向上支持软件的运行&#xff0c;具有承上启下的作用。 4.总结 操作系统…

集合03 Collection (List) - Java

List ArrayListArrayList注意事项ArrayList底层操作机制-源码分析&#xff08;重点&#xff09; VectorVector基本介绍 ——Vector和ArrayList比较Vector底层结构和源码分析 LinkedList基本介绍LinkedList的底层结构和操作机制LinkedList的增删改查 ——LinkedList和ArrayList比…

12.字符串拼接【2023.12.4】

1.问题描述 我们在编程过程中经常会遇到把不同字符串拼接在一起的情况&#xff0c;从而更直观地展示给用户我们所要表达的信息。本题将给出两个字符串&#xff0c;请依次将这两个字符串拼接在一起。 2.解决思路 用字符串拼接符 进行连接两个字符串 3.代码实现 str1input(…

我的创作三周年纪念日

今天收到CSDN官方的来信&#xff0c;创作三周纪念日到了。 Dear: Hann Yang &#xff0c;有幸再次遇见你&#xff1a; 还记得 2020 年 12 月 12 日吗&#xff1f; 你撰写了第 1 篇技术博客&#xff1a; 《vba程序用7重循环来计算24》 在这平凡的一天&#xff0c;你赋予了它…

【异常解决】SpringBoot + Maven 在 idea 下启动报错 Unable to start embedded Tomcat(已解决)

Unable to start embedded Tomcat&#xff08;已解决&#xff09; 一、背景介绍二、原因分析2.1 网络上整理2.2 其他原因 三、解决方案 一、背景介绍 spring boot(v2.5.14) maven idea 启动项目 之前项目一直启动的好好的&#xff0c;都能正常运行。重启的时候突然就不能启…

鸿蒙(HarmonyOS)应用开发——简易版轮播图

简述 轮播图在应用中&#xff0c;已经很常见的展现方式。像uniapp、iview&#xff0c;viewUI等前端组件框架&#xff0c;都提供了轮播图组件。那么在harmonyOS中&#xff0c;如果要实现轮播&#xff0c;我们是使用swiper 组件 swiper组件 swiper 组件是一种容器组件。它提供…

Linux---虚拟机软件

1. 虚拟机软件的介绍 它是能够虚拟出来计算机的一个软件。 常用虚拟机软件: VmwareVirtualBox 说明: 只有安装了虚拟机软件才可以创建虚拟机&#xff0c;当然通过虚拟机软件还可以创建多个虚拟机。 2. 虚拟机的介绍 就是模拟一个真实的计算机&#xff0c;好比一个虚拟的…
最新文章