easyexcel 导出图片到excel,excel无法筛选

b4wnujal  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(99)

导出图片到excel,由于不是嵌入到单元格内的,导致对excel作筛选时,图片一直存在。

flvlnr44

flvlnr441#

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

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class EmbedImageInExcel {

    public static void main(String[] args) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Image");

        // 读取图片文件
        BufferedImage bufferedImage = ImageIO.read(new File("path/to/your/image.jpg"));

        // 将图片转换为字节数组
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "jpg", byteArrayOutputStream);
        byte[] bytes = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.close();

        // 将图片字节数组插入到 Excel 文件中
        int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
        CreationHelper helper = workbook.getCreationHelper();
        Drawing drawing = sheet.createDrawingPatriarch();
        ClientAnchor anchor = helper.createClientAnchor();

        // 设置图片位置和大小
        anchor.setCol1(1);
        anchor.setRow1(1);
        Picture picture = drawing.createPicture(anchor, pictureIdx);
        picture.resize(1, 1); // 调整图片大小以适应单元格

        // 保存 Excel 文件
        try (FileOutputStream fileOut = new FileOutputStream("image_embedded.xlsx")) {
            workbook.write(fileOut);
        }

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

相关问题