Java 中导入带图片的 Excel

在Java中使用apache.poi库导入带有图片的Excel文件可以通过以下步骤完成:

  1. 添加依赖:首先,在您的Java项目中添加apache.poi库的依赖项。您可以在Maven项目的pom.xml文件中添加以下依赖项: 

    <dependency>
     <groupId>org.apache.poi</groupId>
     <artifactId>poi</artifactId>
     <version>4.1.2</version>
    </dependency>
    <dependency>
     <groupId>org.apache.poi</groupId>
     <artifactId>poi-ooxml</artifactId>
     <version>4.1.2</version>
    </dependency>
  2. 创建ExcelImageImporter 类:创建一个类来处理Excel图片数据的导入

    package com.mhw.read.jpg;
    
    /**
     * @program: lomir-ai-box
     * @description:
     * @author: ext.manhengwei1
     * @create: 2023-07-18 15:47
     **/
    
    import org.apache.poi.ss.usermodel.*;
    import org.apache.poi.xssf.usermodel.*;
    import org.apache.poi.util.IOUtils;
    
    import java.io.*;
    
    public class ExcelImageImporter {
        public static void main(String[] args) {
            try {
                FileInputStream fileInputStream = new FileInputStream(new File("C:\Users\ext.manhengwei1\Desktop\1111.xlsx"));
                Workbook workbook = new XSSFWorkbook(fileInputStream);
    
                Sheet sheet = workbook.getSheetAt(0);
    
                Drawing<?> drawing = sheet.getDrawingPatriarch();
                for (Shape shape : drawing) {
                    if (shape instanceof Picture) {
                        Picture picture = (Picture) shape;
                        ClientAnchor anchor = picture.getClientAnchor();
    
                        // 获取图片数据
                        byte[] pictureData = picture.getPictureData().getData();
    
                        // 将图片数据保存到文件
                        String pictureFileName = "C:\Users\ext.manhengwei1\Desktop\picture.jpg";
                        FileOutputStream pictureOutputStream = new FileOutputStream(new File(pictureFileName));
                        IOUtils.copy(new ByteArrayInputStream(pictureData), pictureOutputStream);
                        pictureOutputStream.close();
    
                        System.out.println("图片保存成功:" + pictureFileName);
                    }
                }
    
                workbook.close();
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    
    

在上面的示例中,您需要将"C:\Users\ext.manhengwei1\Desktop\1111.xlsx"替换为实际的Excel文件路径。