POI+JFreeChart生成报表图片在Excel中的位置
2017-12-22 23:22
816 查看
private void genPieChart(HSSFWorkbook workbook, HSSFSheet sheet, List<PieChartData> dataList, String pieChartName) { PieDataset dataSet = createDataset(dataList); JFreeChart chart = createPie2DChart(dataSet, dataList, pieChartName); try { ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); ChartUtils.writeChartAsPNG(byteArrayOut, chart, 600, 600); BufferedImage bufferImg = ImageIO.read(new File(tempPngPath)); ImageIO.write(bufferImg, "png", byteArrayOut); HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 512, 255, (short) 0, 18, (short) 5, 44); anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_DONT_RESIZE); // 插入图片 patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut .toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG)).resize(1); } catch (IOException e) { e.printStackTrace(); } }
1.ChartUtils.writeChartAsPNG(byteArrayOut, chart, 600, 600);
这里的600,600是长和宽,可以适当调整。
2.HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 512, 255,(short) 0, 18, (short) 5, 44);
这行代码是控制位置的关键。官方文档这样解释着8个参数的意思:
Parameters:
dx1 - the x coordinate within the first cell.
dy1 - the y coordinate within the first cell.
dx2 - the x coordinate within the second cell.
dy2 - the y coordinate within the second cell.
col1 - the column (0 based) of the first cell.
row1 - the row (0 based) of the first cell.
col2 - the column (0 based) of the second cell.
row2 - the row (0 based) of the second cell.
可以看到8个参数实际上是4对,dx1和dy1是图片左上角在所在单元格的位置,dx2和dy2是图片右下角在所在单元格的位置,col1和row1是图片左上角在sheet中的位置(列数,行数),col2和row2是图片右上角在sheet的位置(列数,行数)。
因此我们如果要调整图片在Excel中的位置,其实起作用的是后面4个参数,前面4个参数只是在小范围内变动的,影响很小。
看下我这行代码new HSSFClientAnchor(0, 0, 512, 255,(short) 0, 18, (short) 5, 44)的意思。这8个参数表明我的图片的左上角在第1列第19行(A19)(为什么不是第0列第18行?因为Excel的行列数都是从0开始的,这里需要注意一下),图片右下角在第6列第45行(F45)。(0,0)的意思是,左上角在A19这个单元格内的位置是该单元格的左上角,(512,255)的意思是,右下角在F45这个单元格内的位置是右下角(单元格的长大概是宽的两倍)。
简单来说,关注后面4个参数就可以基本确定图表在Excel文档中的位置了。
相关文章推荐
- POI+JFreeChart生成报表图片插入到Excel中
- POI+JFreeChart生成报表图片插入到Excel中
- 使用poi和jfreechart生成excel图表图片
- jfreechart,pdf生成组件iText,jasper report报表组件及POI操作excel等在企业软件开发中常遇到的第三方应用
- javaweb 利用POI生成excel报表 相关代码
- 借助POI实现Java生成并打印报表(Excel)
- 11、借助POI实现Java生成并打印excel报表(2)
- 利用POI获取Excel中图片和图片位置
- poi jxl 生成EXCEL 报表
- poi生成excel报表合并列
- 使用POI生成Excel文件及使用POI在EXCEL文件中插入图片的方法
- 使用POI生成Excel报表
- zk框架获取POI Excel图片 以及 设置图片位置和大小的方法
- 利用POI获取Excel中图片和图片位置(支持excel2003or2007多sheet)
- Excel生成报表之解决方案--插入图片
- POI实现Excel报表,实现下载、图片输出、字体设置
- 使用POI生成Excel报表
- 使用POI生成Excel报表
- poi 读取Excel文件模板生成报表文件
- 关于POI对Excel2007中图片的处理,获取图片在excel中对应的位置