Deena
Deena

Reputation: 297

Exporting Jfreechart image to excel

I am looking for options to export a jfreechart (available in a JSP+struts) to an excel sheet.

I have tried 'setting the response header to type msexcel' to export the entire JSP to excel, but it is not rendering the jfreechart image.

Is there anyother option to export the jfreechart to excel?

Upvotes: 1

Views: 2991

Answers (2)

Eugene Shamkin
Eugene Shamkin

Reputation: 183

Apache POI will not help you because it has a limitiation (read the manual at Apache website). It can plot line and scattered charts only, that's look very poor. Library good for working with excel but not for building a graphs. My suggestion is use prepared in advance templates, adjust it and just transfer necessary data from Java to template. Another way it is use rendered JPEG, but it is horrible things and do not do this.

Upvotes: 0

Deena
Deena

Reputation: 297

I have generated the chart using jfreechart and used POI for exporting it to excel.

ServletOutputStream stream=resp.getOutputStream();
resp.setContentType("application/vnd.ms-excel");
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
int imageWidth= 700;
int imageHeigth = 400;

JFreeChart chart=ChartFactory.createBarChart("Test Chart", "", "", dataset, PlotOrientation.VERTICAL, true, true, false);

ChartUtilities.writeChartAsJPEG(outStream, chart, imageWidth, imageHeigth);

byte[] imageInByte = outStream.toByteArray();
outStream.close();

int pictureIdx =wb.addPicture(imageInByte,Workbook.PICTURE_TYPE_JPEG);

Drawing drawing = sheet.createDrawingPatriarch();

CreationHelper helper = wb.getCreationHelper();

//add a picture shape
ClientAnchor anchor = helper.createClientAnchor();
//set top-left corner of the picture,
//subsequent call of Picture#resize() will operate relative to it
anchor.setCol1(3);
anchor.setRow1(4);
Picture pict = drawing.createPicture(anchor, pictureIdx);

//auto-size picture relative to its top-left corner
pict.resize();
wb.write(outStream);
stream.write(outStream.toByteArray());

Upvotes: 1

Related Questions