使用Java将图片添加到Excel的几种方式

news/2024/6/18 21:35:47 标签: java, excel, python

1、超链接

使用POI,依赖如下

         <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>

Java代码如下,运行该程序它会在桌面创建ImageLinks.xlsx文件。

java">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代码

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列,只需要修改一行代码

java">// 设置固定尺寸
 picture.resize(1, 1);

在这里插入图片描述
看着还是有点别扭,再设置一下宽高,看下效果
在这里插入图片描述
可以看到已经非常Nice了,下面是调整后的代码

java">
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

先看效果
在这里插入图片描述
代码如下:

java">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.niftyadmin.cn/n/5256632.html

相关文章

monaco报错#Unexpected usage at EditorSimpleWorker.loadForeignModule

场景 升级monaco版本&#xff0c;和vue-cli版本&#xff0c;打开.ts后缀的文件&#xff0c;报错 解决 在vue.config.js文件中&#xff0c;添加 chainWebpack(config) {config.plugin("monaco").use(new MonacoWebpackPlugin());},module.exports {...configureW…

Vue router深入学习

Vue router深入学习 一、单页应用程序介绍 1.概念 单页应用程序&#xff1a;SPA【Single Page Application】是指所有的功能都在一个html页面上实现 2.具体示例 单页应用网站&#xff1a; 网易云音乐 https://music.163.com/ 多页应用网站&#xff1a;京东 https://jd.co…

FT-2000/4 UEFI编译

安装依赖 sudo apt-get install make-guile sudo apt-get install make gcc bison flex sudo apt-get install build-essential uuid-dev iasl git gcc-5 nasm python3-distutils编译UEFI 进入edk2-for-support文件夹&#xff0c;依次运行以下命令 ./build2004.sh init # de…

【Linux】tar、zip与rar

前言 我解压过无数的文件&#xff0c;却唯独无法解压自己。 tar tar是一个常用的文件打包和归档工具&#xff0c;它在Linux系统中被广泛使用。它的名称"tar"代表"tape archive"&#xff08;磁带归档&#xff09;&#xff0c;最初用于将多个文件和目录打…

MySQL_8.一级索引,二级索引概述

1.一级索引 索引和数据存储在一起&#xff0c;都存储在同一个Btree中的叶子节点。一般主键索引都是一级索引 2.二级索引 二级索引树的叶子节点存储的是主键而不是数据。也就是说&#xff0c;在找到索引后&#xff0c;得到对应的主键&#xff0c;再回到一级索引中找主键对应的数…

python——第十六天

面向对象——继承 class RichMan(object): def __init__(self): self.money 1000000000 self.company "阿里巴巴" self.__secretary "小蜜" def speak(self): print(f"我对钱不感兴趣&#xff0c;我最后悔的事&#xff0c;就是创建了{self.company…

UE4 .ini文件使用

在需要给配置文件的类中加上config标签&#xff0c;当然变量也要加 在项目的Config下&#xff0c;新建一个Default类的UCLASS中config等于的名字&#xff0c;这里结合上面截图就是DefaultTest 在下面写入 [/Script/项目名/类名] 然后写变量以及对应的值即可

音视频技术开发周刊 | 323

每周一期&#xff0c;纵览音视频技术领域的干货。 新闻投稿&#xff1a;contributelivevideostack.com。 Meta牵头组建开源「AI复仇者联盟」&#xff0c;AMD等盟友800亿美元力战OpenAI英伟达 超过50家科技大厂名校和机构&#xff0c;共同成立了全新的人工智能联盟。以开源为旗号…