Tech Brainwave

A Road Map for Innovative Technologies

Java code to Read an Excel file using POI

Posted by giftsam Posted on Jul - 10 - 2010

Introduction
Apache POI(Poor Obfuscation Implementation) is used to access Microsoft format files and the Horrible Spreadsheet Format(HSSF) is the pure Java implementation of the Excel ‘97(-2007) file format of POI project. HSSF provides a complete Java API for creating, modifying, reading and writing an XLS file. In this article let us see how to read  a Microsoft excel file using java code.

Things You’ll Need

  1. Apache POI jar(Download).
  2. JDK 1.5 and above.
  3. Your Favourite IDE.

Excel file to be read is given in the image below,

sampleexcel.xls

The below java program is used to read the excel file and the classes used in our sample program are POIFSFileSystem, HSSFWorkbook, HSSFSheet, HSSFRow, HSSFCell.

POIFSFileSystem – This class is used to manages the entire life cycle of the filesystem.

HSSFWorkbook – This is the first object constructed used to write/read an excel file.

HSSFSheet - This class is used to create new spreadsheet which is called by HSSFWorkbook .

HSSFRow - This class represents the rows of a spreadsheet.

HSSFCell - This class represents the cell in a row of a spreadsheet.

ExcelSheetReader.java



package com.sample.excel;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

/**
* @author giftsam
*/
public class ExcelSheetReader
{

/**
* This method is used to read the data's from an excel file.
* @param fileName - Name of the excel file.
*/
private void readExcelFile(String fileName)
{
/**
* Create a new instance for cellDataList
*/
List cellDataList = new ArrayList();
try
{
/**
* Create a new instance for FileInputStream class
*/
FileInputStream fileInputStream = new FileInputStream(fileName);

/**
* Create a new instance for POIFSFileSystem class
*/
POIFSFileSystem fsFileSystem = new POIFSFileSystem(fileInputStream);

/*
* Create a new instance for HSSFWorkBook Class
*/
HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem);
HSSFSheet hssfSheet = workBook.getSheetAt(0);

/**
* Iterate the rows and cells of the spreadsheet
* to get all the datas.
*/
Iterator rowIterator = hssfSheet.rowIterator();

while (rowIterator.hasNext())
{
HSSFRow hssfRow = (HSSFRow) rowIterator.next();
Iterator iterator = hssfRow.cellIterator();
List cellTempList = new ArrayList();
while (iterator.hasNext())
{
HSSFCell hssfCell = (HSSFCell) iterator.next();
cellTempList.add(hssfCell);
}
cellDataList.add(cellTempList);
}
}
catch (Exception e)
{
e.printStackTrace();
}
/**
* Call the printToConsole method to print the cell data in the
* console.
*/
printToConsole(cellDataList);
}

/**
* This method is used to print the cell data to the console.
* @param cellDataList - List of the data's in the spreadsheet.
*/
private void printToConsole(List cellDataList)
{
for (int i = 0; i < cellDataList.size(); i++)
{
List cellTempList = (List) cellDataList.get(i);
for (int j = 0; j < cellTempList.size(); j++)
{
HSSFCell hssfCell = (HSSFCell) cellTempList.get(j);
String stringCellValue = hssfCell.toString();
System.out.print(stringCellValue + "\t");
}
System.out.println();
}
}

public static void main(String[] args)
{
String fileName = "C:" + File.separator + "Users" +
File.separator + "Giftsam" + File.separator + "Desktop" +
File.separator + "sampleexcel.xls";
new ExcelSheetReader().readExcelFile(fileName);
}
}

Now let us execute the preceding java program and the results will look like the below in the console,

ID         Name            Qualification        Designation                      Country
1           Gift Sam        MCA                   Software Engineer                 India
2           Laxman        MCA                   Software Engineer                 India
3           Shunmuga   MCA                   SeniorSoftware Engineer    India

Thatsall folks. I hope from this article clearly explains how to read data from an excel file using java code and for writing to an excel file, refer the article Java Code to write to an Excel file using POI. If you find this article is useful  to you, Dont forget to give your valuable comments.

Categories: Excel, Java

52 Responses so far.

  1. gak says:

    very useful
    Thanks!

    Well-loved. Like or Dislike: Thumb up 92 Thumb down 16

    [Reply]

  2. giftsam says:

    @gak
    You are welcome!!

    Well-loved. Like or Dislike: Thumb up 30 Thumb down 8

    [Reply]

  3. nam says:

    thanks

    Well-loved. Like or Dislike: Thumb up 11 Thumb down 3

    [Reply]

  4. SaravanaPandiyan says:

    Very use full if u don’t mind please give the code for how to update the same result to Database.

    Well-loved. Like or Dislike: Thumb up 15 Thumb down 4

    [Reply]

  5. teshome says:

    Hidden due to low comment rating. Click here to see.

    Poorly-rated. Like or Dislike: Thumb up 5 Thumb down 9

    [Reply]

  6. auob says:

    this code is very good tanks

    Hot debate. What do you think? Thumb up 6 Thumb down 3

    [Reply]

  7. piyush says:

    wat if there are multiple tabs in the excel sheet?
    How can i jump to another tab depending on the value found in first tab?

    Hot debate. What do you think? Thumb up 8 Thumb down 9

    [Reply]

  8. Nithya says:

    Thanks Sam. This really cut short my code dev time

    Hot debate. What do you think? Thumb up 5 Thumb down 7

    [Reply]

  9. Jitendra says:

    Its really helpful. Thanks for providing and explaining the use of Poi jar file to read excels.

    Thanks

    Hot debate. What do you think? Thumb up 5 Thumb down 3

    [Reply]

  10. satya says:

    Very use full if u don’t mind please give the code for how to update the same result to Database.

    Thumb up 5 Thumb down 2

    [Reply]

  11. Mudit says:

    Thanks dear for this code.

    Well-loved. Like or Dislike: Thumb up 5 Thumb down 1

    [Reply]

  12. vasudev says:

    awesome..thanks a lot..worked

    Thumb up 4 Thumb down 1

    [Reply]

  13. Sai_Clairvoyance says:

    Thanks dude….but this code works only with excel old formats…any alternatives for excel 2007?

    Well-loved. Like or Dislike: Thumb up 7 Thumb down 2

    [Reply]

  14. shyam says:

    Thanks…

    Thumb up 4 Thumb down 1

    [Reply]

  15. Ahmed says:

    Hi can u help me. My requirement is to print excel file on printer as and when we execute java class.

    I searhed a lot but no use. No open source library to
    print excel file.

    So i thought to convert my excel to pdf first and then let i print my pdf.

    But when am reading excel file like u gave in ur above code. how i can get the cells so that i can get it in pdf..
    please help me

    Thumb up 2 Thumb down 4

    [Reply]

  16. sathishbor@gmail.com says:

    Good code .need treet

    Thumb up 3 Thumb down 1

    [Reply]

  17. sanjay says:

    nice

    Thumb up 3 Thumb down 1

    [Reply]

  18. varma says:

    very very helpful…

    Thumb up 1 Thumb down 0

    [Reply]

  19. Jayanth says:

    Hi,

    This was very useful. What if i want to skip an excel column.Say if i want to skip the Qualifications column.
    How will you do that?

    Thanks,
    Jayanth

    Well-loved. Like or Dislike: Thumb up 5 Thumb down 0

    [Reply]

  20. sri says:

    Do u know how we can read the excel file from an url

    Thumb up 1 Thumb down 1

    [Reply]

  21. Hawk says:

    Hi,
    Getting eror
    non-static variable this cannot be referenced from a static context
    Getting error on the read file
    Well thanks for the code its very useful help me out with the problem thanks again.

    Thumb up 4 Thumb down 1

    [Reply]

  22. Gokul says:

    Nice code snippet. Thanks

    Thumb up 1 Thumb down 1

    [Reply]

  23. June says:

    do you have any sample for webapp like spring + poi.

    the idea, a button on the jsp to download the excel template file which will call a controller. Controller needs to populate some data first before throwing the excel file to the user. problem is that the generated file should not be save in the server but thrown directly to the user.

    Thumb up 1 Thumb down 1

    [Reply]

  24. Chad Darby says:

    If you need to read MS Excel files based on .xslx format then visit the link http://www.luv2code.com/?p=264

    Thumb up 2 Thumb down 1

    [Reply]

  25. Madhubabu says:

    Thank u very much….

    Thumb up 1 Thumb down 1

    [Reply]

  26. K.SatyamReddy says:

    I want to retrive data from database in to excel sheet.

    Actually the data is very large. So i want to store the data into different worksheet.

    For example:
    ************
    In my table i have 100 rows. So 50 rows in first work sheet and next 50 rows in second work sheet in same Excel Sheet.

    Please replay.

    Thanks & Regards
    SatyamReddy K.

    Thumb up 2 Thumb down 1

    [Reply]

  27. Kinjan Ajudiya says:

    Hello….
    My name is Kinjan Ajudiya.
    I have implemented this and working fine . Now my requirement is some what complex.In that once i read file i took text from file now i will change some text in excel file and with out manually saving file i want updated text ..

    Is that possible ?
    If yes please let me know.
    Thanks and Regards
    Kinjan Ajudiya

    Thumb up 1 Thumb down 0

    [Reply]

  28. Abirami Subramanian says:

    hai,
    ihave downloaded the apache poi jar from the link specified here,but dont know to include it in my java application.please help me to overcome package org.apache.poi.hssf.usermodel does not exists error.please give me instrustions to include the particular package and run the code.

    Thumb up 3 Thumb down 0

    [Reply]

  29. prashant says:

    Hi All,

    It’s working fine (read xls file from java). I want to insert into database using struts2. in my case bean class variables are private Long id;
    private String registrationNo;
    private Date registrationDate;
    private String name;
    private String address;
    private int age;
    private String education;
    private String occupation;
    private String jointOrNuclearFamily;
    private String typesOfProblems;
    private int noOfSession;
    private String assistance;
    private String closedOrPending;
    private String closedOutcome;

    how can i store the data in database. pls help me if anybody know.

    Thumb up 1 Thumb down 0

    [Reply]

  30. Sensi says:

    Your Program is grate! It is very useful to me. I use it to read xls files I save from Open office Calc. It works nicely. But now I use Libre Office Calc to save same xls files in same format. When I use same program, Output of that is not the cell content but like ‘org.apache.poi.hssf.usermodel.HSSFCell@13d422d’ What is my error?

    Thumb up 1 Thumb down 2

    [Reply]

  31. Binod says:

    Thanks All,

    It is really helpful.

    Thumb up 1 Thumb down 0

    [Reply]

  32. andre says:

    Very use full if u don’t mind please give the code for how to update the same result to Database.

    Thumb up 1 Thumb down 0

    [Reply]

  33. sam says:

    can you show me how to do this in C++

    thank you

    Thumb up 1 Thumb down 0

    [Reply]

  34. Mudit says:

    Nice blog….. nice help… thanks a lot Giftsam

    Thumb up 1 Thumb down 0

    [Reply]

  35. saravanan says:

    to display the data in horizontal alignment

    Thumb up 2 Thumb down 0

    [Reply]

  36. lijo says:

    Awesome! just like i needed..

    Thumb up 1 Thumb down 0

    [Reply]

    Ranjith g Reply:

    Hi,

    have u tried inserting integer values

    Thumb up 0 Thumb down 0

    [Reply]

  37. Sumit says:

    Thanks for Vry Gud explaination….

    Thumb up 1 Thumb down 0

    [Reply]

  38. velpari says:

    hi,
    I wanna to print only first 5 fields from the table ,how it is possible

    Thumb up 1 Thumb down 0

    [Reply]

  39. Aiman says:

    Hi All,

    Where to install the POI files?.its not even in a .exe format, its simply a zip file.
    where to extract those files? im getting error at the import line where im trying to import the POI files system and the HSSF row, cell etc.

    anyone please help.

    thanks in advance. :)

    Thumb up 3 Thumb down 0

    [Reply]

  40. Ganapathy says:

    Pls help me out how to copy data from excel to db

    Thumb up 1 Thumb down 0

    [Reply]

  41. Ashwini says:

    Hi very nice and helpful articel

    Thumb up 1 Thumb down 0

    [Reply]

  42. RAMESH says:

    Hi

    i have one query

    sno sname phone
    1 xxxxx xxxxx
    2 xxxxx xxxxx
    3 xxxxx xxxxx

    i wish to search for a column like ( sname)
    i want to get total data under sname column

    How i can do this……..

    Please help me

    Thumb up 0 Thumb down 0

    [Reply]

  43. Rameshwar Kadam says:

    Thanks a lot for this…

    Thumb up 0 Thumb down 0

    [Reply]

  44. nish says:

    working good.. Thanks

    Thumb up 0 Thumb down 0

    [Reply]

  45. Rahul says:

    sir is there any code in java by which we can password protect the excel file that we do normally by giving the password in security settings….

    Thumb up 0 Thumb down 0

    [Reply]

  46. Rodrigo says:

    Hi, i download the POI.jar from:

    http://www.jarfinder.com/index.php/jars/versionInfo/1395

    and just add it to my project.

    After run it i have the following exception:

    Invalid header signature; read 1688935826934608, expected -2226271756974174256………………..

    Can somebody help me? thx

    Thumb up 0 Thumb down 0

    [Reply]

  47. Rohit says:

    This code fails when I run it on server . In local it is working fine

    Thumb up 0 Thumb down 0

    [Reply]

  48. Ranjith says:

    Hi,

    It is reading only String values, it is not loading int values

    Thumb up 0 Thumb down 0

    [Reply]

  49. Rita says:

    the code is very valuable,can u please help how to save excel data to database using hibernate.how to set object object properties from cell valus

    Thanks
    Rita Saluja

    Thumb up 0 Thumb down 0

    [Reply]

  50. INDRA says:

    The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)
    IS THE ERROR WHICH I AM GETTING
    CAN U PLEASE HELP ME OUT ?

    THANKS.

    Thumb up 0 Thumb down 0

    [Reply]