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

We are discussing how to create charts in Java using Apache POI library and JFreechart. We introduced you to the basic concepts and chart creation approach in Part - 1 of this tutorial series. In this part, we will get into the coding act. We will take each and every step we introduced in Part -1 and write the Java Program behind this and see the chart in action. Let us get started.

Read Chart Data in Excel Objects:


The chart data is available in a spreadsheet for us. So, we have to read it into logical Java objects at this step. This is a very simple step and the code fragment to do this is provided below:
                /* 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);

At the end of this step, we also initialize the Pie Dataset object, that will read the data from the input spread sheet and frame the logical data input to the chart.

                /* Create JFreeChart object that will hold the Pie Chart Data */
                DefaultPieDataset my_pie_chart_data = new DefaultPieDataset();


Populate Pie Chart Data from Excel


We created Pie Dataset in the step earlier. Now, we loop through the chart data through an Iterator object, and add the chart data into the Pie Dataset by using "setValue" method. The Java code that does this is shown below:
                /* 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 Chart and Write to OutputStream


All good until now. We have read the Excel chart data successfully into a dataset. With this, we will be able to create a chart and write it to an output stream. We can then read the data back and add the chart to the Excel sheet.
                /* 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 don't want to create an intermediate file on the disk, which could be costly. So, we write the data to the output stream.

That completes Part - 2 of the tutorial. We have so far read the Pie Chart data from Excel and created a chart successfully, and wrote the chart to the output stream. In the next part we will discuss how to read the chart from the output stream, and write the chart into XLS file. Check out Part - 3 of the tutorial in the links below.
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