Login:  Password:    
forgot my password
sign up!
Search: 

Reading Excel file with Java

In this article you will learn how create a program to read an excel file and show the excel data on a frame.

62 6

Suppose you have an excel sheet on which you want to perform some processing. Now it would be much easy if you drag the data from excel and apply the logic on the data obtained to obtain results.

Program Explanation:

First we will include all the import classes.

Note: You need to download the apache poi library for availing the excel functionality. The site for the same is poi.apache.org

Listing 1: Importing classes

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;

BufferedInputStream is used for obtaining the buffered input, IOException is for reporting of input output exceptions, Iterator is used to iterate over the values of the result obtained from the sheet, POIFSFileSystem is the main class of the POIFS system; it manages the entire life cycle of the filesystem.

HSSFCell is representation of a cell in a row of a spreadsheet, HSSFSheet is representation of a worksheet, HSSFWorkbook is representation of a workbook and HSSFRow is representation of a row of a spreadsheet.

Now we will define the class along with main method:

Listing 2: Class name and and main method

    public static void main( String [] args ) {
        try {
   
        	 InputStream input = new BufferedInputStream(
        		        new FileInputStream("sample.xls"));
            POIFSFileSystem fs = new POIFSFileSystem( input );
            HSSFWorkbook wb = new HSSFWorkbook(fs);
            HSSFSheet sheet = wb.getSheetAt(0);

In the code above we defined the main method and make an object of InputStream which points to the excel file which we want to read.

We define an object of POIFSFileSystem which takes the input as the InputStream object.Now we define a new workbook. This workbook will contain the sheets from the excel file.

Now we make the HSSFSheet object called sheet and pass the first sheet from the excel file and we will iterate through each row and column of the sheet and then display the result.

Listing 3: Itearting and displaying the results from sheet

Iterator rows = sheet.rowIterator(); 
            while( rows.hasNext() ) {   
                HSSFRow row = (HSSFRow) rows.next();
                System.out.println("\n");
                Iterator cells = row.cellIterator();
                while( cells.hasNext() ) {
                	
                    HSSFCell cell = (HSSFCell) cells.next();
                    if(HSSFCell.CELL_TYPE_NUMERIC==cell.getCellType())
                    System.out.print( cell.getNumericCellValue()+"     " );
                    else
                    if(HSSFCell.CELL_TYPE_STRING==cell.getCellType())
                        System.out.print( cell.getStringCellValue()+"     " );
                    else
                    	if(HSSFCell.CELL_TYPE_BOOLEAN==cell.getCellType())
                    	System.out.print( cell.getBooleanCellValue()+"     " );
                    	else
                    		if(HSSFCell.CELL_TYPE_BLANK==cell.getCellType())
                            	System.out.print( "BLANK     " );
                            	else
                    		System.out.print("Unknown cell type");
                  
                }
                
                
            }
           
            
        } catch ( IOException ex ) {
            ex.printStackTrace();
        }
    }
    
}

We iterate through each row of the sheet and store that information in variable called rows.

Now we define a while function to read all the rows obtained and use the rows.next() function to obtain the next row and iterate through each column of the row and obtain the column using the next method.

Now we obtain the type of data in that particular column like HSSFCell.CELL_TYPE_NUMERIC is for the numeric data in that particular column. HSSFCell.CELL_TYPE_STRING is for the string data in that particular column.

HSSFCell.CELL_TYPE_Boolean is for the boolean value in that particular column. HSSFCell.CELL_TYPE_BLANK is for the blank data in that particular column.

We put the whole code inside a try catch block to handle the exceptions.

Output :

Reading Excel File

Full Source code:

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;

public class ReadExcel {

    public static void main( String [] args ) {
        try {
   
        	 InputStream input = new BufferedInputStream(
        		        new FileInputStream("sample.xls"));
            POIFSFileSystem fs = new POIFSFileSystem( input );
            HSSFWorkbook wb = new HSSFWorkbook(fs);
            HSSFSheet sheet = wb.getSheetAt(0);
            
            
            Iterator rows = sheet.rowIterator(); 
            while( rows.hasNext() ) {   
                HSSFRow row = (HSSFRow) rows.next();
                System.out.println("\n");
                Iterator cells = row.cellIterator();
                while( cells.hasNext() ) {
                	
                    HSSFCell cell = (HSSFCell) cells.next();
                    if(HSSFCell.CELL_TYPE_NUMERIC==cell.getCellType())
                    System.out.print( cell.getNumericCellValue()+"     " );
                    else
                    if(HSSFCell.CELL_TYPE_STRING==cell.getCellType())
                        System.out.print( cell.getStringCellValue()+"     " );
                    else
                    	if(HSSFCell.CELL_TYPE_BOOLEAN==cell.getCellType())
                    	System.out.print( cell.getBooleanCellValue()+"     " );
                    	else
                    		if(HSSFCell.CELL_TYPE_BLANK==cell.getCellType())
                            	System.out.print( "BLANK     " );
                            	else
                    		System.out.print("Unknown cell type");
                  
                }
                
                
            }
           
            
        } catch ( IOException ex ) {
            ex.printStackTrace();
        }
    }
    
}

Hope you like the article. See you next time.


Anurag Jain
My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified
5 comments have been posted.   Add your comment
[Fechar]

Este post é fechado - você precisa ter acesso ao post para incluir um comentário.

Nirmal
Hi, I have created the JAVA application as you post in this blog.I have few doubts. 1) where we have to put that(.xls file)? I means in which directory? I think in the same directory where my program file is exists. am I right ? 2) I am a user of Open Office Org.So is this application works fine for (.ods file)? 3) Code compile successfully but after that it asked for to select JAVA application.When i select my application nothing will happens in console. Please suggest me and correct me if i am wrong in first step.
[+1 month ago]    Answer it
 
Mr.Bool Editor
We contacted the author of the article and he will answer your question soon.
[+1 month ago]   Answer it
 
[author] Anurag Jain
Answer for your query: 1)Put xls in same directory from where you run the application 2)No it cannot work for ods. 3)for running ensure you have xls file named sample.xls and also while running you are placing all jar dependency. Thanks
[+1 month ago]   Answer it
 
Meeris
Hi Anurag, I am using Java transformation in informatica for the first time. I am trying to read the Excel workbook and generate seperate sheets using java code in the Java Transformation. I am getting an error saying "ILLEGAL START OF EXPRESSION" and pointing out at public class ExcelParser and private static final String JAVA_TOSTRING = "EEE MMM dd HH:mm:ss zzz yyyy"; and public ExcelParser(HSSFSheet sheet). I am not able to make out whats going wrong here. Below is the java code. It also displays a message " ; expected at public class ExcelParser". It also displays a message " } expected". Could you pls help out? // Java imports import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.*; // Apache POI - HSSF imports import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; In the on Input Row tab i have placed the below code: public class ExcelParser { HSSFSheet m_sheet; int m_iNbRows; int m_iCurrentRow = 0; private static final String JAVA_TOSTRING = "EEE MMM dd HH:mm:ss zzz yyyy"; public ExcelParser(HSSFSheet sheet) { m_sheet = sheet; m_iNbRows = sheet.getPhysicalNumberOfRows(); } /* Returns the contents of an Excel row in the form of a String array. * @see com.ibm.ccd.common.parsing.Parser#splitLine()*/ public String[] splitLine() throws Exception { if (m_iCurrentRow == m_iNbRows) return null; HSSFRow row = m_sheet.getRow(m_iCurrentRow); if(row == null) { return null; } else { int cellIndex = 0; int noOfCells = row.getPhysicalNumberOfCells(); String[] values = new String[noOfCells]; short firstCellNum = row.getFirstCellNum(); short lastCellNum = row.getLastCellNum(); if (firstCellNum >=0 && lastCellNum >=0) { for(short iCurrent = firstCellNum; iCurrent [+1 month ago]    Answer it
 
[author] Anurag Jain
Please attach the full source codes you tried.I can correct the codes as soon as i get a glimpse of the code you are trying. But yeah i assume the problem is compile time.And most probably you have missed a } after a function or class ending. I can provide more specific answer once i see the full codes you tried. Thanks
[+1 month ago]   Answer it
 
Help us to improve! Give us your feedback:

Give your note to this post: 1 2 3 4 5 6 7 8 9 10
Is this post helpful? Yes No



[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits








mrbool.com
contact us   |   publish your post   |   buy credits

Copyright 2013 - all rights reserved to www.web-03.net