
packagetest;importorg.apache.poi.xssf.usermodel.XSSFClientAnchor;importorg.apache.poi.xssf.usermodel.XSSFDrawing;importorg.apache.poi.xssf.usermodel.XSSFSheet;importorg.apache.poi.xssf.usermodel.XSSFWorkbook;importjavax.imageio.ImageIO;importjava.awt.image.BufferedImage;import java.io.*;importjava.util.HashMap;importjava.util.Map;public classWriteImgUtil {
public static void whiteImg(XSSFDrawing patriarch, XSSFWorkbook wb, String filepath, CellPoint cellPoint) throwsIOException {
ByteArrayOutputStream byteArrayOut= newByteArrayOutputStream();
BufferedImage bufferImg= ImageIO.read(newFile(filepath));
ImageIO.write(bufferImg, filepath.substring(filepath.lastIndexOf(".") + 1), byteArrayOut);//起点坐标
int x1 =cellPoint.getRow1();int y1 =cellPoint.getCol1();//终点坐标
int x2 =cellPoint.getRow2();int y2 =cellPoint.getCol2();//anchor主要用于设置图片的属性
XSSFClientAnchor anchor1 = new XSSFClientAnchor(0, 0, 0, 0, (short) x1, y1, (short) x2, y2);//插入图片
int index =wb.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_PICT);
patriarch.createPicture(anchor1, index);
}public static classCellPoint {//起点横坐标
private introw1;//起点纵坐标
private intcol1;//终点横坐标
private introw2;//终点纵坐标
private intcol2;public CellPoint(int row1, int col1, int row2, intcol2) {this.row1 =row1;this.col1 =col1;this.row2 =row2;this.col2 =col2;
}public intgetRow1() {returnrow1;
}public void setRow1(introw1) {this.row1 =row1;
}public intgetCol1() {returncol1;
}public void setCol1(intcol1) {this.col1 =col1;
}public intgetRow2() {returnrow2;
}public void setRow2(introw2) {this.row2 =row2;
}public intgetCol2() {returncol2;
}public void setCol2(intcol2) {this.col2 =col2;
}
}
public static void addImageToExcel(File file, Integer sheetIndex, Mapmap) {
FileOutputStream fileOut= null;try{
FileInputStream inputstream= newFileInputStream(file);
XSSFWorkbook wb= newXSSFWorkbook(inputstream);
XSSFSheet sheet1=wb.getSheetAt(sheetIndex);//画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)
XSSFDrawing patriarch =sheet1.createDrawingPatriarch();for (Map.Entryentry : map.entrySet()) {
String key= entry.getKey(); //图片路径
CellPoint point = entry.getValue(); //图片插入坐标
whiteImg(patriarch, wb, key, point);
}
fileOut= newFileOutputStream(file);//写入excel文件
wb.write(fileOut);
}catch(Exception e) {
e.printStackTrace();
}finally{if (fileOut != null) {try{
fileOut.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}public static void main(String[] args) throwsIOException {
Map map = new HashMap<>();
map.put("D:\1.png",new CellPoint(5,13,7,14));
addImageToExcel(new File("D:\2.xlsx"),0,map);
System.out.println("ok");
}
}