您的位置:首页 > 其它

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文档中的位置了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jfreechart poi