gpt4 book ai didi

java - Apache POI 插入图像

转载 作者:搜寻专家 更新时间:2023-10-30 19:40:36 25 4
gpt4 key购买 nike

我在制作 Excel 表格时遇到问题。关于这个主题有很多问题,但我根本无法弄清楚我做错了什么。我的代码运行,没有显示任何错误,但我没有看到插入的图像 :(

代码如下:

    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();
}

最佳答案

问题是你的 anchor 不正确。您需要设置所有 4 个值,因为默认值为 0 - 但您的第一列不能比第二列更正确;)您将得到负范围。当您打开 excel 文件时,您应该会收到一条警告,指出它已损坏。

那么试试

anchor.setCol1(2);
anchor.setCol2(3);
anchor.setRow1(3);
anchor.setRow2(4);

来 self 编写的一些代码的工作示例:

// 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();

关于java - Apache POI 插入图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21991473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com