本次使用的poi为easyexcel中的poi。以下为easyexcel的版本号及对应的poi版本。
<!-- 只需导入其中一个 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
<!-- 只需导入其中一个 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<!-- 只需导入其中一个 -->
写一个controller 接受导入的execl文件
@PostMapping("/uploadImageFile")
public Result uploadImageFile(@RequestParam("file") MultipartFile file) throws IOException {
if (ObjectUtil.isEmpty(file)) {
return Result.error("参数不能为空");
}
// 如果execl的格式不是xlsx 使用 HSSFWorkbook
XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
XSSFSheet sheet = workbook.getSheetAt(0);
Map<String, PictureData> pictures = getPictures(sheet);
// 遍历sheet
for (Row row : sheet) {
// 排除第一行表头
if (row.getRowNum() == 0) {
continue;
}
// 获取对应列
String imageKey = row.getRowNum() + ":" + "2";
if (pictures.containsKey(imageKey)) {
PictureData pictureData = pictures.get(imageKey);
byte[] image = pictureData.getData();
// 通过hutool工具把图片保存到指定位置
FileUtil.writeBytes(image, "E:/pic/" + row.getRowNum() + "与2" + ".png");
}
}
return Result.success();
}
写一个独立的方法获取sheet中所有的图片文件,此处是使用 行下标 + ":" + 列下标
private static Map<String, PictureData> getPictures(XSSFSheet sheet) {
Map<String, PictureData> picMap = new HashMap<>();
List<XSSFShape> list = sheet.getDrawingPatriarch().getShapes();
if (CollectionUtil.isEmpty(list)) {
return picMap;
}
for (XSSFShape hssfShape : list) {
// 过滤出图片的数据
if (hssfShape instanceof XSSFPicture) {
XSSFPicture xssfPicture = (XSSFPicture) hssfShape;
XSSFClientAnchor xssfClientAnchor = (XSSFClientAnchor) xssfPicture.getAnchor();
PictureData pictureData = xssfPicture.getPictureData();
picMap.put(xssfClientAnchor.getRow1() + ":" + xssfClientAnchor.getCol1(), pictureData);
}
}
return picMap;
}
以下进行接口测试及测试结果