Apache POI:将图像添加到包含图表的工作表中

时间:2013-09-29 18:07:18

标签: java apache-poi

使用Apache POI,我可以将图像添加到没有图表的工作表中,但它不能与带图表的工作表一起使用

问题:无法通过excel打开输出文件!

为什么不呢?有解决方案吗?

InputStream inputStreamXls = new FileInputStream("c:\\temp\\template.xls");
XSSFWorkbook workbook = new XSSFWorkbook(inputStreamXls);
XSSFSheet sheet = workbook.getSheetAt(0);
inputStreamXls.close();

InputStream inputStreamImg = new FileInputStream("c:\\temp\\logo.png");
byte[] bytes = IOUtils.toByteArray(inputStreamImg);
int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
inputStreamImg.close();

CreationHelper helper = workbook.getCreationHelper();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(x);
anchor.setRow1(y);
Picture pict = drawing.createPicture(anchor, pictureIdx);

// save workbook
String file = "c:\\temp\\output_file.xls";
FileOutputStream fileOut = new FileOutputStream(file);
workbook.write(fileOut);
fileOut.close();

1 个答案:

答案 0 :(得分:0)

您的代码使用XSSFWorkbook来读写.xls文件。 XSSFWorkbook适用于.xlsx文件。使用HSSFWorkbook。