Read 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.

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.io.*;
import java.util.*;
import org.jfree.data.*;
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;
import org.jfree.data.category.DefaultCategoryDataset;

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("")){
try{ 
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)); 
} 
i++; 
} 
}catch(Exception e){ 
System.out.println(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.");
}
}
}

Ads