Sunday, January 8, 2012

Read Excel file using apache POI library

If you want to read Excel file in Java, Apache POI is the library which supports to read/write microsoft documents. Here is the code to read an Excel file.
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;

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.ss.usermodel.Row;

public class ReadExcel {
 
 public static void main(String[] args){
  
  try{
   InputStream myxls = new FileInputStream("C:\\exceltest.xls");
   HSSFWorkbook wb     = new HSSFWorkbook(myxls);
   
   HSSFSheet sheet = wb.getSheetAt(0); 
   
   Iterator rows = sheet.rowIterator();
   
   System.out.println("Total Rows :: " + sheet.getLastRowNum());
   
   //Iterate over each row
   while (rows.hasNext()) 
   {
    HSSFRow row = (HSSFRow) rows.next();
    if(checkIfRowEmpty(row)) 
     continue;
    
    int minColIndex = row.getFirstCellNum();
    int maxColIndex = row.getLastCellNum();
    
    for(int colIndex = minColIndex; colIndex <= maxColIndex; colIndex++) 
    {
     HSSFCell cell = row.getCell(colIndex);
     
     // POI can't recognize empty cells of Excel, so we should create new cells with a blank value
     if(cell == null) 
     {
        cell = row.createCell(colIndex);
           cell.setCellValue(" ");
     }    
     String value = "";
     
     switch(cell.getCellType())
     {
      case HSSFCell.CELL_TYPE_NUMERIC:
       value = Double.toString(cell.getNumericCellValue());
       break;
      case HSSFCell.CELL_TYPE_BOOLEAN:
       value = Boolean.toString(cell.getBooleanCellValue());
       break;
      case HSSFCell.CELL_TYPE_BLANK:
       value = "";
       break;
      case HSSFCell.CELL_TYPE_ERROR:
       value = "";
       break;
      case HSSFCell.CELL_TYPE_FORMULA:
       value = "";
       break;
      default:
       value = cell.getStringCellValue();
       break;
     }
     System.out.print(value + "|");
    }
    System.out.println();
   }
  }
  catch(Exception e){
   e.printStackTrace();
  }
 }
 
 public static boolean checkIfRowEmpty(HSSFRow row) 
 {
  int minColumIndex = row.getFirstCellNum();
  int maxColumnIndex = row.getLastCellNum();
  
  boolean isRowEmpty = true;
  for(int columIndex = minColumIndex; columIndex <= maxColumnIndex; columIndex++) 
  {
   HSSFCell cell = row.getCell(columIndex);
   if(cell == null || cell.toString().trim().isEmpty() || cell.toString().length() == 0){
    
   }
   else{
    isRowEmpty = false;
    return isRowEmpty;
   }
  }
  return isRowEmpty;
 }
}

No comments: