Create Chart in Excel - Java POI Example Program - Part 4

This is the last part of the Pie Chart creation in Excel in Java, using POI and JFreeChart. We have provided a step by step guide to creating Pie Chart in Part 2 and Part 3 of this post. In the final part of this series, we will provide the complete Java Program for this example and a sample output.

Create Pie Chart in Excel - Java - Apache POI / JFreeChart Example Program


The full program that reads an Excel sheet for chart data source and writes the chart back to the worksheet is provided below:

import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.*;
import org.apache.poi.util.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.jfree.data.general.DefaultPieDataset; 
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartUtilities; 
import java.util.Iterator;
public class CreatePieChartExample {  
        public static void main(String[] args) throws Exception{
                
                /* Read Excel and the Chart Data */
                FileInputStream chart_file_input = new FileInputStream(new File("my_chart.xls"));
                /* Read data into HSSFWorkbook */
                HSSFWorkbook my_workbook = new HSSFWorkbook(chart_file_input);
                /* This worksheet contains the Pie Chart Data */
                HSSFSheet my_sheet = my_workbook.getSheetAt(0);
                /* Create JFreeChart object that will hold the Pie Chart Data */
                DefaultPieDataset my_pie_chart_data = new DefaultPieDataset();
                /* We now iterate over the Excel Workbook data and Populate Pie Chart Data */
                /* Create an Iterator object */
                Iterator<Row> rowIterator = my_sheet.iterator(); 
                /* Loop through worksheet data and populate Pie Chart Dataset */
                String chart_label="a";
                Number chart_data=0;            
                while(rowIterator.hasNext()) {
                        //Read Rows from Excel document
                        Row row = rowIterator.next();  
                        //Read cells in Rows and get chart data
                        Iterator<Cell> cellIterator = row.cellIterator();
                                while(cellIterator.hasNext()) {
                                        Cell cell = cellIterator.next(); 
                                        switch(cell.getCellType()) { 
                                        case Cell.CELL_TYPE_NUMERIC:
                                                chart_data=cell.getNumericCellValue();
                                                break;
                                        case Cell.CELL_TYPE_STRING:
                                                chart_label=cell.getStringCellValue();
                                                break;
                                        }
                                }
                /* Add data to the data set */          
                my_pie_chart_data.setValue(chart_label,chart_data);
                }               
                /* Create a logical chart object with the chart data collected */
                JFreeChart myPieChart=ChartFactory.createPieChart("Excel Pie Chart Java Example",my_pie_chart_data,true,true,false);
                /* Specify the height and width of the Pie Chart */
                int width=640; /* Width of the chart */
                int height=480; /* Height of the chart */
                float quality=1; /* Quality factor */
                /* We don't want to create an intermediate file. So, we create a byte array output stream 
                and byte array input stream
                And we pass the chart data directly to input stream through this */             
                /* Write chart as JPG to Output Stream */
                ByteArrayOutputStream chart_out = new ByteArrayOutputStream();          
                ChartUtilities.writeChartAsJPEG(chart_out,quality,myPieChart,width,height);
                /* We now read from the output stream and frame the input chart data */
                InputStream feed_chart_to_excel=new ByteArrayInputStream(chart_out.toByteArray());
                byte[] bytes = IOUtils.toByteArray(feed_chart_to_excel);
                /* Add picture to workbook */
                int my_picture_id = my_workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
                /* We can close Piped Input Stream. We don't need this */
                feed_chart_to_excel.close();
                /* Close PipedOutputStream also */
                chart_out.close();
                /* Create the drawing container */
                HSSFPatriarch drawing = my_sheet.createDrawingPatriarch();
                /* Create an anchor point */
                ClientAnchor my_anchor = new HSSFClientAnchor();
                /* Define top left corner, and we can resize picture suitable from there */
                my_anchor.setCol1(4);
                my_anchor.setRow1(5);
                /* Invoke createPicture and pass the anchor point and ID */
                HSSFPicture  my_picture = drawing.createPicture(my_anchor, my_picture_id);
                /* Call resize method, which resizes the image */
                my_picture.resize();
                /* Close the FileInputStream */
                chart_file_input.close();               
                /* Write changes to the workbook */
                FileOutputStream out = new FileOutputStream(new File("my_chart.xls"));
                my_workbook.write(out);
                out.close();            
        }
}
This program has all the steps we have discussed we have discussed in earlier parts, and is tested working. Let us see an example output for this program.

Pie Chart Java Excel Program - Example Output


The output of the program for the input we specified in Part - 1, is provided below:

Create Pie Chart in Excel - Java -Apache POI / JFreeChart - Example Output
Create Pie Chart in Excel - Java -Apache POI / JFreeChart - Example Output

That completes an interesting series on creating charts in Excel documents with Apache POI  / JFreeChart. We will see an XLSX version of this example soon. And see some more different charts as we move on. If you have any comments on this tutorial, you can post it in the comments section. Like us on Facebook and never miss a technical tutorial.
This Tutorial: How to Add a Chart to Excel Document in Java with POI?
Keywords: Apache POI Chart Example, JFreeChart, Create Chart in Excel Using Java, Create Chart in POI  Example.
Parts:
  1. Adding Charts in Apache POI - Introduction
  2. Step by Step Guide to Creating Charts
  3. Step by Step Guide to Creating Charts - Contd
  4. Full Java Program Example with Output

No comments:

Post a Comment