将图片添加到 Excel 单元格时,Apache POI-HSSF 会扭曲图像大小 [英] Apache POI-HSSF distorts image size when adding picture into Excel cell

查看:85
本文介绍了将图片添加到 Excel 单元格时,Apache POI-HSSF 会扭曲图像大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Apache POI-HSSF 将图片添加到单元格中.图像是 120x100,但无论我做什么以及如何调整它的大小,Excel 电子表格总是显示它跨越多行并将其扭曲为高度大于宽度.

I am adding a picture into a cell using Apache POI-HSSF. The image is 120x100 but no matter what I do and how I resize it, the Excel spreadsheet always shows it spanning multiple rows and distorts it to a much bigger height than width.

如何保持原始尺寸?

我的代码:

InputStream is = new FileInputStream(getImageURL());
byte[] bytes = IOUtils.toByteArray(is);
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
is.close();

//add a picture shape
CreationHelper helper = wb.getCreationHelper();
ClientAnchor anchor = helper.createClientAnchor();
// Create the drawing patriarch.  This is the top level container for all shapes.
Drawing drawing = sheet1.createDrawingPatriarch();
//set top-left corner of the picture,
//subsequent call of Picture#resize() will operate relative to it

anchor.setAnchorType(0);
anchor.setCol1(1);
anchor.setRow1(1);

Picture pict = drawing.createPicture(anchor, pictureIdx);

//auto-size picture relative to its top-left corner
pict.resize();

我已经尝试了所有 dx/dy 坐标和 Col/Row.位置无关紧要,问题在于它会水平拉伸图像.

I've tried all dx/dy coordinates and Col/Row. The position doesn't matter, the problem it stretches the image horizontally.

推荐答案

我遇到了类似的问题,我添加的图像变得扭曲.我试过 pict.resize() 和 sheet.autoSizeColumn() 但它没有用.最后我找到了以下网址:-https://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/examples/ss/AddDimensionedImage.java

I had been facing the similar issue where the image I added was getting distorted. I tried pict.resize() and sheet.autoSizeColumn() but it didn't work. Finally I found the below URL:- https://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/examples/ss/AddDimensionedImage.java

我将上述类添加到我的代码中,并使用它的方法将图像添加到 excel 中.我能够添加几乎没有失真的图像.希望这对你也有帮助.我写了下面的代码:-

I added the above class into my code and used it's method to add the image into excel. I was able to add the image with little distortion. Hope this helps to you also. I wrote below code:-

BufferedImage imageIO = ImageIO.read(new URL(image));
int height= imageIO.getHeight();
int width=imageIO.getWidth();
int relativeHeight=(int)(((double)height/width)*28.5);
new AddDimensionedImage().addImageToSheet(2,  sheet.getPhysicalNumberOfRows()-1 , sheet, sheet.createDrawingPatriarch(),new URL(image), 30, relativeHeight, AddDimensionedImage.EXPAND_ROW);

这篇关于将图片添加到 Excel 单元格时,Apache POI-HSSF 会扭曲图像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆