Press enter to see results or esc to cancel.

Java read xls- Read data from Java excel API JAVA

  1. This Java program shows how to read Excel file. Please note that this program will read only .xls file and will not read .xlsx file. You can convert a .xlsx to .xls by clicking Save As and select the Save as type ‘Excel 97-2003 Workbook (*.xls)’.
  2. This program uses poi-3.9-20121203.jar. You can download it here poi-3.9-20121203. Add this jar to Classpath
  3. Project Structure in Eclipse
    import java.util.Iterator;
    import java.util.Vector;
    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;
    public class Read_From_Excel { 
    public static void main( String [] args ) {
    	String fileName="C:\\test.xls"; 
    	//Read an Excel File from C:\\test.xls and Store in a Vector
        Vector dataHolder=readExcelFile(fileName);
        //Print the data read
    public static Vector readExcelFile(String fileName)
        /** --Define a Vector
            --Holds Vectors Of Cells
        Vector cellVectorHolder = new Vector();
        /** Creating Input Stream**/
        //InputStream myInput= ReadExcelFile.class.getResourceAsStream( fileName );
        FileInputStream myInput = new FileInputStream(fileName);
        /** Create a POIFSFileSystem object**/
        POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
        /** Create a workbook using the File System**/
         HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
         /** Get the first sheet from workbook**/
        HSSFSheet mySheet = myWorkBook.getSheetAt(0);
        /** We now need something to iterate through the cells.**/
          Iterator rowIter = mySheet.rowIterator();
              HSSFRow myRow = (HSSFRow);
              Iterator cellIter = myRow.cellIterator();
              Vector cellStoreVector=new Vector();
                  HSSFCell myCell = (HSSFCell);
        }catch (Exception e){e.printStackTrace(); }
        return cellVectorHolder;
    private static void printCellDataToConsole(Vector dataHolder) {
    	try {  
        for (int i=0;i<8000; i++){
                   Vector cellStoreVector=(Vector)dataHolder.elementAt(i);
            for (int j=0; j < cellStoreVector.size();j++){
                HSSFCell myCell = (HSSFCell)cellStoreVector.elementAt(j);
                String stringCellValue = myCell.toString();
                System.out.print(j+" "+stringCellValue+"\t");
               //Print Each cell here
    	} catch (Exception e) {
    		// TODO Auto-generated catch block
  5. test.xls
  6. Output in Console
  7. Download the Project here.