获取表格中每一行的图片并用姓名命名
代码如下:
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPicture;
import org.apache.poi.hssf.usermodel.HSSFShape;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
@Slf4j
public class MyExcelUtil {
public static void main(String[] args) throws IOException {
new MyExcelUtil().getPictures();
}
public void getPictures() throws IOException {
ExcelReader reader = ExcelUtil.getReader(new File("C:\\Users\\Administrator\\Desktop\\pictures.xls"));
HSSFSheet sheet = (HSSFSheet) reader.getSheet();
List<HSSFShape> children = sheet.getDrawingPatriarch().getChildren();
for (int i = 0; i < children.size(); i++) {
HSSFShape child = children.get(i);
HSSFPicture picture = (HSSFPicture) child;
HSSFClientAnchor clientAnchor = picture.getClientAnchor();
// 获取图片所在的首行数和尾行数
int row1 = clientAnchor.getRow1();
int row2 = clientAnchor.getRow2();
System.out.println(StrUtil.format("图片{}:row1 = {}, row2 = {}", i, row1, row2));
// 获取行中的姓名
String name = sheet.getRow(row2).getCell(1).getStringCellValue();
System.out.println("获取到图片所在行的姓名:" + name);
// 写入新文件
File file = new File(name + ".png");
byte[] data = picture.getPictureData().getData();
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(data);
outputStream.flush();
outputStream.close();
}
}
}
输出日志:
图片0:row1 = 0, row2 = 0
获取到图片所在行的姓名:张三
图片1:row1 = 1, row2 = 2
获取到图片所在行的姓名:王五
图片2:row1 = 3, row2 = 5
获取到图片所在行的姓名:孙
输出图片:
![]() |