private void drawPictureInfoExcel(HSSFWorkbook wb, HSSFPatriarch patriarch, String pictureUrl, int rowIndex) {
// rowIndex代表当前行
try {
if (pictureUrl != null) {
DataInputStream dis = null;
dis = new DataInputStream(new FileInputStream (URLDecoder.decode("C:/logs/1565079224(1).jpg","UTF-8")));
byte[] data = new byte [1024];
dis.read(data);
// anchor主要用于设置图片的属性
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 1, rowIndex, (short) 1,rowIndex);
// Sets the anchor type (图片在单元格的位置)
// 0 = Move and size with Cells, 2 = Move but don't size with
// cells, 3 = Don't move or size with cells.
patriarch.createPicture(anchor, wb.addPicture(data, HSSFWorkbook.PICTURE_TYPE_JPEG));
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
debug 图片二进制流是没问题的,但是导出到文档后就如下图所示了!
```
两个错误:
1、图片长宽有问题,你看下 HSSFClientAnchor的构造方法里的参数,导致图片显示不全,可能你rowIndex=0,高度就没了。
2、图片的字节流不完整,你这样read,读取的不够全面,也只读了1M.
我贴上我写的demo,你参考一下
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("图片");
Drawing patriarch = sheet.createDrawingPatriarch();
if (pictureUrl != null) {
//写入流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
FileInputStream fileInputStream = new FileInputStream(new File(pictureUrl));
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 anchor = new HSSFClientAnchor(0, 0, 255, 0, (short) x, y, (short) (x + width), (y + height));
patriarch.createPicture(anchor, wb.addPicture(outputStream.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
}
OutputStream os = new FileOutputStream(new File("E:\\test.xlsx"));
wb.write(os);
看代码没什么问题,你拉伸一下 Excel 的这个单元格看看,是不是区域太小看不到图片呢?
流flush or close