Java实现导入带有图像的 Excel 文件

本文介绍了如何使用ApachePOI库在Java中读取Excel文件,提取其中的图像数据,定位其在工作表中的位置,并将这些图像保存到本地文件系统。作者通过详细步骤展示了从读取文件到保存图片的完整过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、准备一个Excel文件

假设我们有一个简单的 Excel 文件,其中包含图像及其名称的列表。

2、使用的工具

    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>5.2.3</version>
    </dependency>

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
    </dependency>

3、解析 Excel 文件

现在我们将完成读取 Excel 文件、提取数据和处理图像的代码。

3.1、读取文件

InputStream in = Test.class.getResourceAsStream("/excel/12.xlsx");

Java 有多种读取文件的方法。上面代码是仅读取位于类路径中的文件。

3.2、 创建XSSFWorkbook对象

try (XSSFWorkbook workbook = new XSSFWorkbook(in)) {
    XSSFSheet sheet = workbook.getSheetAt(0);
    ...
}

这通过在内存中缓冲整个流来构造一个工作簿对象。代表 sheet工作簿的第一张工作表。

3.3、提取图像

            XSSFDrawing patriarch = sheet.createDrawingPatriarch();
            List<XSSFShape> shapes = patriarch.getShapes();
            Map<Integer, byte[]> imageByLocations = shapes.stream()
                    .filter(Picture.class::isInstance)
                    .map(s -> (Picture) s)
                    .map(this::toMapEntry)
                    .collect(Collectors.toMap(Pair::getKey, Pair::getValue));

图像不会保存在工作表的单元格中,而是保存在名为 XSSFDrawing(POI 行话中)的 SpreadsheetML Drawing中。您可以将 SpreadsheetML Drawing视为用于放置形状的画布。从父级(SpreadsheetML drawing)中,您可以获取所有形状。形状可以是图片,也可以是连接器、图形框架等等。由于我们这次只针对图片,因此我们过滤形状 .filter(Picture.class::isInstance)。下一步是通过 this::toMapEntry 找出图片位于哪一行。最后,我们构建一个包含行号和图像字节的map。

3.4、查找图像位置

Pair<Integer, byte[]> toMapEntry(Picture picture) {
    byte[] data = picture.getPictureData().getData();
    ClientAnchor anchor = picture.getClientAnchor();
    return Pair.of(anchor.getRow1(), data);
}

由于形状没有放置在单元格中,因此我们需要找到它们的锚定位置。形状的左上角 (anchor.getRow1()) 为我们提供了行号。我们构建一个中间对象 org.apache.commons.lang3.tuple.Pair,它允许我们构建map。

3.5 、迭代每一行

List<Image> images = StreamSupport.stream(sheet.spliterator(), false)
        .filter(this::isNotHeader)
        .map(row -> new Image(row.getCell(0).toString(), imageByLocations.get(row.getRowNum())))
        .collect(toList());

我们迭代每一行以提取单元格内容。在我们的例子中,只有文件名存储在第一个单元格row.getCell(0).toString()(索引 0)中。通过行号,我们可以从上一步构建的地图中获取图像。

3.6、保存图片

images.forEach(image -> {
        String pathname = String.format("%s/%s.jpg", System.getProperty("user.home"), image.fileName);
        FileUtils.writeByteArrayToFile(new File(pathname), image.bytes);
    });

最后一步是将图像写入文件系统。为了示例,我们将图像写入主文件夹中。

4、完整代码

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFShape;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import static java.util.stream.Collectors.toList;

public class Test {
    public static void main(String[] args) throws IOException {
        InputStream in = Test.class.getResourceAsStream("/excel/12.xlsx");
        new Test().importExcel(in);
    }

    void importExcel(InputStream in) throws IOException {
        try (XSSFWorkbook workbook = new XSSFWorkbook(in)) {
            XSSFSheet sheet = workbook.getSheetAt(0);
            XSSFDrawing patriarch = sheet.createDrawingPatriarch();
            List<XSSFShape> shapes = patriarch.getShapes();
            Map<Integer, byte[]> imageByLocations = shapes.stream()
                    .filter(Picture.class::isInstance)
                    .map(s -> (Picture) s)
                    .map(this::toMapEntry)
                    .collect(Collectors.toMap(Pair::getKey, Pair::getValue));

            List<Image> images = StreamSupport.stream(sheet.spliterator(), false)
                    .filter(this::isNotHeader)
                    .map(row -> new Image(row.getCell(0).toString(), imageByLocations.get(row.getRowNum())))
                    .collect(toList());

            for (Image image : images) {
                try {
                    String pathname = String.format("%s/%s.jpg", System.getProperty("user.home"), image.fileName);
                    FileUtils.writeByteArrayToFile(new File(pathname), image.bytes);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    boolean isNotHeader(Row row) {
        return !row.getCell(0).toString().toLowerCase().contains("name");
    }

    Pair<Integer, byte[]> toMapEntry(Picture picture) {
        byte[] data = picture.getPictureData().getData();
        ClientAnchor anchor = picture.getClientAnchor();
        return Pair.of(anchor.getRow1(), data);
    }

    static class Image {
        String fileName;
        byte[] bytes;

        Image(String fileName, byte[] bytes) {
            this.fileName = fileName;
            this.bytes = bytes;
        }
    }
}

### Java实现图片Excel 文件导入 在处理包含图片Excel 文件时,可以借助 Apache POI 库来读取和解析复杂的 Excel 文档。Apache POI 提供了对二进制数据的支持,因此能够有效地处理嵌入对象如图像。 对于 Spring Boot 项目而言,在 `pom.xml` 需要引入如下依赖以支持操作 Excel 文件中的图片[^1]: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.3</version> </dependency> ``` 为了实现这一功能,下面是一个简单的例子展示如何创建一个服务类用于上传并解析含有图片的工作表: #### 创建 Controller 接口接收文件上传请求 定义 RESTful API 来接受客户端提交的带有图片Excel 表格作为 multipart/form-data 请求的一部分: ```java @RestController @RequestMapping("/api/excel") public class FileUploadController { @PostMapping("/uploadWithImage") public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file){ try { new FileService().processExcelWithImages(file.getInputStream()); return ResponseEntity.ok("成功"); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()); } } } ``` #### 封装 Service 方法处理具体逻辑 编写业务层代码负责实际的数据提取工作,这里会遍历所有的 sheet 并查找其中可能存在的 Drawing 物件(即图形元素),进而获取到每张图的信息: ```java @Service class FileService{ void processExcelWithImages(InputStream inputStream)throws IOException{ Workbook workbook = null; try { workbook = new XSSFWorkbook(inputStream); int numberOfSheets = workbook.getNumberOfSheets(); for(int i=0;i<numberOfSheets ;i++){ Sheet sheet =workbook.getSheetAt(i); Iterator<PictureData> picturesIterator = getPictureData(sheet); while(picturesIterator.hasNext()){ PictureData pictureData=picturesIterator.next(); byte[] data =pictureData.getData(); // 获取图片字节数组 String suggestedFileName = pictureData.suggestFileExtension(); // 获得推荐扩展名 System.out.println(String.format( "发现 %s 类型的图片, 大小为 %d 字节.", suggestedFileName.toUpperCase(),data.length)); saveImageToFile(data,"output."+suggestedFileName); // 存储至本地磁盘或其他存储介质中 } } } finally { if(workbook!=null) workbook.close(); } } private static void saveImageToFile(byte[] imageData,String fileName){ Path path = Paths.get(fileName); try(OutputStream outStream = Files.newOutputStream(path)){ outStream.write(imageData); }catch(IOException ex){ throw new UncheckedIOException(ex); } } /** * Helper method to extract all images from a given sheet. */ private static Iterable<PictureData>getPictureData(Sheet sheet){ List<PictureData> result=new ArrayList<>(); Drawing<?> drawing=sheet.createDrawingPatriarch(); for(Drawing<?>.Shape shape :drawing.getChildren()){ if(shape instanceof Picture){ Picture pic=(Picture)shape; result.add(pic.getPictureData()); } } return result; } } ``` 上述代码片段展示了如何通过迭代器访问每一个 sheet 上面的所有形状,并判断其是否属于 Picture 对象;如果是,则进一步调用相应的方法取得该图片的相关属性以及原始二进制流以便后续保存或显示出来。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值