Thursday, March 28, 2013

To make bar chart from excel sheet in java?


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.");
  }
 }
}

2 comments:

  1. Java lovers’ gona love it, Check it out.... JavaOne 2013 is apparently being held at Hyderabad this year as well (8-9 May) at the same place guys…. They have also started accepting registrations (check this: https://www.regpulse.com/javaone2013/register.php?pcode=737266&src=4003&Act=1 )

    ReplyDelete
  2. thank you so much ...please what can the error for I do all the steps but the result an empty charts

    ReplyDelete