Friday, 13 April 2012

Read Excel File Using Apache POI

Here is some nice code snippet to read Excel file using Apache POI Api.
Download Apache POI form here
Create a project in eclipse and add following jars in your classpath. (Not all are required for this example)
poi-3.8-20120326.jar
poi-examples-3.8-20120326.jar
poi-excelant-3.8-20120326.jar
poi-ooxml-3.8-20120326.jar
poi-ooxml-schemas-3.8-20120326.jar
poi-scratchpad-3.8-20120326.jar
commons-logging-1.1.jar
junit-3.8.1.jar
log4j-1.2.13.jar
package com.bharat.poi;

package com.bharat.poi;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadExcelFile
{
  public static void main(String... args)
  {
    // name of Excel file you want to read.
    String fileName = "bond-2-8.xlsx";
    
    // Read an Excel File and Store in an ArrayList
    ArrayList<ArrayList<XSSFCell>> dataHolder = readExcelFile(fileName);
    
    // Print the data read
    printCellDataToConsole(dataHolder);
  }

  public static ArrayList<ArrayList<XSSFCell>> readExcelFile(String fileName)
  {
    /**
     * --Define a List --Holds List Of Cells
     */
    ArrayList<ArrayList<XSSFCell>> cellListHolder =
        new ArrayList<ArrayList<XSSFCell>>();

    try
    {
      /* Creating Input Stream */
      FileInputStream myInput = new FileInputStream(fileName);

      /* Create a workbook using Stream */
      XSSFWorkbook myWorkBook = new XSSFWorkbook(myInput);

      /* Get the first sheet from workbook */
      XSSFSheet mySheet = myWorkBook.getSheetAt(0);

      /* iterate through the cells. */
      
      Iterator rowIter = mySheet.rowIterator();

      while (rowIter.hasNext())
      {
        XSSFRow myRow = (XSSFRow) rowIter.next();
        Iterator cellIter = myRow.cellIterator();
        ArrayList<XSSFCell> cellStoreList = new ArrayList<XSSFCell>();
        while (cellIter.hasNext())
        {
          XSSFCell cell = (XSSFCell) cellIter.next();
          cellStoreList.add(cell);
        }
        cellListHolder.add(cellStoreList);
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return cellListHolder;
  }

  /**
   * prints data to console
   * 
   * @param dataHolder
   */
  private static void printCellDataToConsole(ArrayList<ArrayList<XSSFCell>> dataHolder)
  {

    for(ArrayList<XSSFCell> cellList : dataHolder)
    {
      for(XSSFCell cell: cellList)
      {
        String stringCellValue = cell.toString();
        System.out.print(stringCellValue +"\t");
      }
      System.out.println();
    }

  }
}


15 comments:

  1. I got below exception when I tried your example. Any idea what I did wrong? Thank you very much for your help!

    Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/xssf/usermodel/XSSFWorkbook
    at ReadExcelFile.readExcelFile(ReadExcelFile.java:38)
    at ReadExcelFile.main(ReadExcelFile.java:18)
    Caused by: java.lang.ClassNotFoundException: org.apache.poi.xssf.usermodel.XSSFWorkbook
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 2 more

    I have these jar files in my path:
    commons-logging-1.1.jar
    dom4j-1.6.1.jar
    junit-3.8.1.jar
    log4j-1.2.13.jar
    poi-3.8-20120326.jar
    poi-examples-3.8-20120326.jar
    poi-excelant-3.8-20120326.jar
    poi-ooxml-3.8-20120326.jar
    poi-ooxml-schemas-3.8-20120326.jar
    poi-scratchpad-3.8-20120326.jar
    stax-api-1.0.1.jar
    xmlbeans-2.3.0.jar

    ReplyDelete
    Replies
    1. Hi Lei,
      Looks like it is not able to load a class file from poi-ooxml-3.8-20120326.jar

      Can you please check your eclipse classpath and see if you see jars added in the classpath.

      if you are using maven for your project please run following maven command to add jars to your project's classpath.

      mvn eclipse:eclipse

      let me know if you still face issues.

      Delete
  2. Very Interesting and Informative blog about Java..

    Java Training in Chennai

    ReplyDelete
  3. I found this informative and interesting blog so i think so its very useful and knowledge able.I would like to thank you for the efforts you have made in writing this article.
    python training in chennai
    python course institute in chennai

    ReplyDelete
  4. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject

    rpa training in chennai |rpa course in chennai|
    rpa training in bangalore | best rpa training in bangalore | rpa course in bangalore | rpa training institute in bangalore | rpa training in bangalore | rpa online training

    ReplyDelete
  5. Thank you for sharing such great information with us. I really appreciate everything that you’ve done here and am glad to know that you really care about the world that we live in
    Python Online certification training
    python Training institute in Chennai
    Python training institute in Bangalore

    ReplyDelete
  6. It seems you are so busy in last month. The detail you shared about your work and it is really impressive that's why i am waiting for your post because i get the new ideas over here and you really write so well.

    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

    ReplyDelete
  7. Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.
    Data Science Training in Chennai
    Robotic Process Automation Training in Chennai
    Cloud Computing Training in Chennai
    Data Warehousing Training in Chennai
    Dev Ops Training in Chennai

    ReplyDelete
  8. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    Java Training in Electronic City

    ReplyDelete
  9. Really is an amazing contents..,thanks for sharing a valuable information like this,your team followed a unique method for everything..keep moving...!

    Android Training in Chennai

    Android Online Training in Chennai

    Android Training in Bangalore

    Android Training in Hyderabad

    Android Training in Coimbatore

    Android Training

    Android Online Training

    ReplyDelete
  10. Great explanation, your content inspired me and waiting for the next blog. Thanks for sharing.Thank you for taking the time to share this valuable information. Really helpful.

    Data Science Training In Chennai

    Data Science Online Training In Chennai

    Data Science Training In Bangalore

    Data Science Training In Hyderabad

    Data Science Training In Coimbatore

    Data Science Training

    Data Science Online Training

    ReplyDelete