下面展示一些 内联代码片
。
int x = 9; //列总数
int y = 8; //行总数
//单元格高度
double heightRow = (cell.getRow().getHeightInPoints() / 72) * 96; //80
//单元格宽度
double widthRow = sheetPicture.getColumnWidth(cell.getColumnIndex()) / 32; //86
byte[] fileContentBmp = SystemUtil.fileConvertToByteArray("D:/a1.png"); 测试
if(fileContentBmp.length <= 0){ //没图片不处理
break;
}
InputStream in = new ByteArrayInputStream(fileContentBmp);
BufferedImage ms = ImageIO.read(in);
double imageOriginalWidth = ms.getWidth();//原始图片的长度
double imageOriginalHeight = ms.getHeight();//原始图片的宽度
double allHeight = heightRow * y; //合并单元格总高
double allWidth = widthRow * x; //合并单元格总宽
/**
* 1.把高满铺,计算宽是否超出
* 2.不超出,计算宽占得格总数,在中间画
* 3.超出,那么把宽满铺,计算高的格子总数,在中间画
*/
HSSFClientAnchor anchor = null;
double proportion= allHeight / imageOriginalHeight; //比例
double estimateWidth = imageOriginalWidth * proportion; // 高满铺时要求宽那么多
if(estimateWidth <= allWidth){ //2.不超出,计算宽占得格总数,在中间画
double actWidth = allHeight*(imageOriginalWidth / imageOriginalHeight);
double actWidthCount = actWidth / widthRow; //需要的行数
double side = (x - actWidthCount) / 2;
int sideInt = (int) Math.round(side);
anchor = new HSSFClientAnchor(10, 10, 1000, 250,
(short) (cell.getColumnIndex()+sideInt), cell.getRowIndex(), //开始坐标
(short) ((short) cell.getColumnIndex() + x-sideInt-1), cell.getRowIndex() + y-1); // 结束坐标获取不到,只能累加
}else { //3.超出,那么把宽满铺,计算高的格子总数,在中间画
double actHeight = allWidth/(imageOriginalWidth / imageOriginalHeight);
double actHeightCount = actHeight / heightRow; //需要的行数
double top = (y-actHeightCount)/2;
int topInt = (int) Math.round(top);
anchor = new HSSFClientAnchor(10, 10, 1000, 250,
(short) (cell.getColumnIndex()), cell.getRowIndex()+topInt, //开始坐标
(short) ((short) cell.getColumnIndex() + x-1), cell.getRowIndex() + y-topInt-1); // 结束坐标获取不到,只能累加
}
// 插入图片
HSSFPatriarch patriarch = sheetPicture.createDrawingPatriarch();
patriarch.createPicture(anchor, workbook.addPicture(fileContentBmp,HSSFWorkbook.PICTURE_TYPE_JPEG));