记录一次POI导出图片到excel部分图片显示一个点
显示有问题的代码
InputStream is = new FileInputStream(projectPath+path[pathItem]);
byte[] bytes = IOUtils.toByteArray(is);
// int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_DIB);
int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
CreationHelper helper = workbook.getCreationHelper();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(j);
anchor.setRow1((i + 2));
//anchor.setAnchorType(3);
// 获取原图片的宽度和高度,单位都是像素
//File image = new File(projectPath+(String)map.get("p"+rowNameList.get(j-1)));
File image = new File(projectPath+path[pathItem]);
String massge=(String)map.get("depart")+(String)map.get("office")+(String)map.get("name")+"图片格式:"+new MimetypesFileTypeMap().getContentType(image);
System.out.println(massge);
BufferedImage sourceImg = ImageIO.read(image);
double imageWidth = sourceImg.getWidth();
double imageHeight = sourceImg.getHeight();
// 获取单元格宽度和高度,单位都是像素
// sheet.getColumnWidthInPixels找不到
double cellWidth = sheet.getColumnWidth( cell.getColumnIndex());
// getHeightInPoints()方法获取的是点(磅),就是excel设置的行高,1英寸有72磅,一般显示屏一英寸是96个像素
double cellHeight = cell.getRow().getHeightInPoints() / 72 * 96;
// 插入图片,如果原图宽度大于最终要求的图片宽度,就按比例缩小,否则展示原图
Picture pict = drawing.createPicture(anchor, pictureIdx);
//比较单元格高度和图片高度
if (imageHeight > cellHeight) {
// 最终图片大小与单元格宽度的比例
double scaleY =cellHeight/imageHeight;
pict.resize(scaleY);
} else {
pict.resize();
}
图片显示正常的代码
Drawing patriarch = sheet.createDrawingPatriarch();
//写入流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
FileInputStream fileInputStream = new FileInputStream(new File(projectPath+path[pathItem]));
byte[] data = new byte[1024];
int len = 0;
while ((len = fileInputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
int x = 1;
int y = 1;
int width = 6;
int height = 10;
// anchor主要用于设置图片的属性
HSSFClientAnchor anchor2 = new HSSFClientAnchor(0, 0, 255, 255, (short) x, y, (short) (x + width), (y + height));;
if(pathItem>0){
anchor2= new HSSFClientAnchor(300, 0, 600, 255, (short) x, y, (short) (x + width), (y + height));
}
anchor2.setCol1(j);
anchor2.setCol2(j);
anchor2.setRow1((i + 2));
anchor2.setRow2((i + 2));
patriarch.createPicture(anchor2, workbook.addPicture(outputStream.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
分析
主要是要理解HSSFClientAnchor 的构造参数
HSSFClientAnchor anchor2 = new HSSFClientAnchor(0, 0, 255, 255, (short) x, y, (short) (x + width), (y + height));