[英]Apache POI insert image
I am having troubles with inserting a picture in an excel sheet im making. 我在制作excel表中插入图片时遇到了麻烦。 There are a lot of question about this subject, but I simply cannot figure out what am I doing wrong.
关于这个问题有很多问题,但我根本无法弄清楚我做错了什么。 My code runs, shows no errors but I do not see an image inserted :(
我的代码运行,显示没有错误,但我没有看到插入的图像:(
here is the code: 这是代码:
InputStream is = new FileInputStream("nasuto_tlo.png");
byte [] bytes = IOUtils.toByteArray(is);
int pictureIndex = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
is.close();
CreationHelper helper = wb.getCreationHelper();
Drawing drawingPatriarch = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(2);
anchor.setRow1(3);
Picture pict = drawingPatriarch.createPicture(anchor, pictureIndex);
pict.resize();
try {
FileOutputStream out = new FileOutputStream(root+"/Busotina/Busotina1.xls");
wb.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
the problem is that your anchor is not correct. 问题是你的锚不正确。 You need to set all 4 values, because the default ones are 0 - but your first column can not be more right than your second one ;) You'll get negative extent.
您需要设置所有4个值,因为默认值为0 - 但是您的第一列不能比第二列更正确;)您将获得负面范围。 You should get a warning when you open the excel file that it is corrupt.
当您打开Excel文件已损坏时,您应该收到警告。
So try 所以试试吧
anchor.setCol1(2);
anchor.setCol2(3);
anchor.setRow1(3);
anchor.setRow2(4);
A working example from some code I wrote: 我写的一些代码的工作示例:
// read the image to the stream
final FileInputStream stream =
new FileInputStream( imagePath );
final CreationHelper helper = workbook.getCreationHelper();
final Drawing drawing = sheet.createDrawingPatriarch();
final ClientAnchor anchor = helper.createClientAnchor();
anchor.setAnchorType( ClientAnchor.MOVE_AND_RESIZE );
final int pictureIndex =
workbook.addPicture(IOUtils.toByteArray(stream), Workbook.PICTURE_TYPE_PNG);
anchor.setCol1( 0 );
anchor.setRow1( LOGO_ROW ); // same row is okay
anchor.setRow2( LOGO_ROW );
anchor.setCol2( 1 );
final Picture pict = drawing.createPicture( anchor, pictureIndex );
pict.resize();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.