示例代码
excel文件格式 : xlsx
public static Map<String, XSSFPictureData> getPictures(Sheet sheet) throws Exception {
Map<String, XSSFPictureData> pictures = new HashMap<>();
// 对于XLSX文件
if (sheet instanceof XSSFSheet) {
XSSFDrawing drawing = ((XSSFSheet) sheet).getDrawingPatriarch();
List<XSSFShape> shapes = drawing.getShapes();
for (XSSFShape shape : shapes) {
if (shape instanceof XSSFPicture) {
XSSFPicture picture = (XSSFPicture) shape;
XSSFClientAnchor anchor = (XSSFClientAnchor) picture.getAnchor();
XSSFPictureData pdata = picture.getPictureData();
String key = anchor.getRow1() + "-" + anchor.getCol1();
pictures.put(key, pdata);
}
}
}
// 对于XLS文件,逻辑类似,使用HSSF相关类
return pictures;
}
public static void savePicture(XSSFPictureData pictureData, String outputPath) throws Exception {
String extension = pictureData.suggestFileExtension();
byte[] data = pictureData.getData();
FileOutputStream out = new FileOutputStream(outputPath + "." + extension);
IOUtils.write(data, out);
out.close();
}
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\Administrator\\Documents\\0708.xlsx");
try (InputStream inputStream = new FileInputStream(file)) {
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
Map<String, XSSFPictureData> pictures = getPictures(sheet);
for (Map.Entry<String, XSSFPictureData> entry : pictures.entrySet()) {
savePicture(entry.getValue(), "D:\\" + entry.getKey());
}
}
}