Create Chart in Excel - Java POI Example Program

Adding Charts in Apache POI - Introduction


One of the limitations in Apache POI is the ability to add charts (At the time of writing.). That does not prevent us from adding a chart to Excel as an Image, if we want the chart to be static and does not need the chart to change when the underlying data changes. In this tutorial, we will explain how to use JFreeChart, an open source chart API with Apache POI and add a chart image to the Excel document. (XLS Example). We have written a lot about JFreechart so we will focus on basics. We will create a Pie Chart based on Excel Data, and add the Pie Chart back to the Excel document. Sounds interesting? Let us get started. 

The chart data is available in Excel spreadsheet as per below:

Base Chart Data - Java - POI - JFreeChart- Chart Example - Input
Base Chart Data - Java - POI - JFreeChart- Chart Example - Input
We will create a Pie Chart out of this data and save it back to the same document.

Charts - JFreechart - POI- High  level steps


It could turn out to be a sizeable Java program. So, let us write the steps we have to do, and then start coding it step by step. The high level steps are documented below:

  1. Read Excel Chart Data in HSSF objects.
  2. Push Pie Chart Data into DefaultPieDataset object of JFreeChart.
  3. Create Pie Chart in JFreeChart.
  4. Read Pie Chart as an Image in Apache POI.
  5. Convert Chart Data to byte Array.
  6. Create Drawing Canvas and Insert Chart Picture into Excel Spreadsheet.
  7. Write Chart data back to Excel and Save the Document.
  8. Repeat all these steps and create a XLSX chart example
I guess we have got all the steps in there. Pretty much what we want to get our first chart into XLS using Apache POI. Let us now give a go against each of the steps, and hope the outcome is fruitful.

Excel Charts in Java - Required JAR Files


You will need POI v3.8 (or equivalent) and JFreechart 1-0,14 to work out the chart example. The list of JAR files that you need for this tutorial is provided below:

jfreechart-1.0.14.jar
jcommon-1.0.17.jar
poi-3.8.jar
poi-ooxml-3.8.jar
poi-ooxml-schemas-3.8.jar
dom4j-1.6.1.jar
xmlbeans-2.3.0.jar
commons-codec-1.7.jar

You will get all these with POI / JFreeChart, except commons-codec-1.7.jar. You have to download this separately from Apache.

 If you have read all these introduction and are ready to give a go, then head to part -2 of this tutorial series.

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

1 comment:

  1. Can this create a bar graph as well?

    ReplyDelete