Share on Google+Share on Google+

Read Excel file and generate bar graph

In this tutorial, you will learn how to read an excel file and generate bar graph.

Read Excel file and generate bar graph

In this tutorial, you will learn how to read an excel file and generate bar graph. Here is an example that reads an excel file using POI api and store the data into array list. We have created the array list for each column(depends on the number of columns) and using the data of excel file, we have generated a bar chart. The given code uses Apache POI api and Jfreechart api.

import java.util.*;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.plot.PlotOrientation;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ReadExcel{
public static void main(String[]args){
short a=0; 
short b=1; 
int i=0; 
ArrayList<Integer> list1=new ArrayList<Integer>();
ArrayList<Integer> list2=new ArrayList<Integer>();
int x=0, y=0; 
String filename ="C:/data.xls"; 
if(filename != null && !filename.equals("")){
FileInputStream fs =new FileInputStream(filename); 
HSSFWorkbook wb = new HSSFWorkbook(fs); 
for(int k = 0; k < wb.getNumberOfSheets(); k++){ 
int j=i+1; 
HSSFSheet sheet = wb.getSheetAt(k); 
int rows = sheet.getPhysicalNumberOfRows(); 
for(int r = 1; r < rows; r++){ 
HSSFRow row = sheet.getRow(r); 
int cells = row.getPhysicalNumberOfCells(); 
HSSFCell cell1 = row.getCell(a); 
x =(int) cell1.getNumericCellValue(); 
HSSFCell cell2 = row.getCell(b); 
y =(int) cell2.getNumericCellValue(); 

list1.add(new Integer(x));
list2.add(new Integer(y)); 
}catch(Exception e){ 


DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for(int j=0;j<list1.size();j++){
dataset.setValue((double)list2.get(j), "Marks", list1.get(j).toString());
JFreeChart chart = ChartFactory.createBarChart("BarChart using JFreeChart","ID", "Marks", dataset, 
PlotOrientation.VERTICAL, false,true, false);
try {
ChartUtilities.saveChartAsJPEG(new File("C:/chart.jpg"), chart,400, 300);
} catch (IOException e) {
System.out.println("Problem in creating chart.");


Posted on: December 20, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null