使用 Apache POI 库可以轻松地在 Excel 文件中添加图片并设置图片与单元格的边距。以下示例代码演示了如何将图片插入单元格并自定义其位置和大小:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ExcelImageExample {
    public static void main(String[] args) throws IOException {
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();

        // 创建工作表
        Sheet sheet = workbook.createSheet('Sheet1');

        // 加载图片文件
        InputStream inputStream = new FileInputStream('path_to_image.jpg');
        byte[] imageBytes = IOUtils.toByteArray(inputStream);

        // 将图片插入到单元格中
        int pictureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_JPEG);
        inputStream.close();

        CreationHelper helper = workbook.getCreationHelper();
        Drawing<?> drawing = sheet.createDrawingPatriarch();
        ClientAnchor anchor = helper.createClientAnchor();

        // 设置图片与单元格的边距
        anchor.setCol1(0);  // 图片所在的起始列
        anchor.setRow1(0);  // 图片所在的起始行
        anchor.setCol2(1);  // 图片所在的结束列
        anchor.setRow2(1);  // 图片所在的结束行

        anchor.setDx1(10);  // 设置左边距
        anchor.setDy1(10);  // 设置上边距
        anchor.setDx2(10);  // 设置右边距
        anchor.setDy2(10);  // 设置下边距

        Picture picture = drawing.createPicture(anchor, pictureIdx);
        picture.resize();  // 自动调整图片尺寸

        // 保存工作簿到文件
        FileOutputStream fileOut = new FileOutputStream('path_to_output_file.xlsx');
        workbook.write(fileOut);
        fileOut.close();

        // 关闭工作簿
        workbook.close();
    }
}

请确保将'path_to_image.jpg'替换为实际的图片文件路径,将'path_to_output_file.xlsx'替换为输出的Excel文件路径。此代码将创建一个新的Excel文件,并在第一个单元格中插入指定的图片,并设置图片与单元格的边距。

Apache POI Excel:添加图片并设置单元格边距

原文地址: https://www.cveoy.top/t/topic/p9hE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录