Wednesday, December 12, 2012

Read any Row in Excel - HSSF POI


This function helps to read any row in excel using HSSF POI. Instantiate this class in your main class and call ReadRow (int, int) function by providing row & column value as parameters.
Anatomy of ReadRow () function
·         Parameters – Two integers, Former denoting row & Later for column to be referenced
·         Return value – String Value of the corresponding cell
Here we go with implementation..
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 java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ExcelRead
{
                                public ExcelRead()           {}
       public String ReadRow(int i ,int j)    {
                FileInputStream  inputStream=null;
                String cellvalue=null;     
                try
                {              //Input File to be read    
                    inputStream = new FileInputStream ("Input.xls");
                }
                catch (FileNotFoundException e)
                {
                System.out.println ("File not found in the specified path.");
                e.printStackTrace ();
                }
               
                try
                {
                HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
              // Get the first sheet on the workbook.
              HSSFSheet sheet = workbook.getSheetAt(0);
              HSSFRow row=sheet.getRow(i);       
             HSSFCell myCell = row.getCell(j);            
             cellvalue=myCell.toString();        
                }
                catch(Exception e)
                {
              System.out.println ("IO Exception");
                e.printStackTrace ();
                }
                                return cellvalue;        
    }
  
    public static void main(String[] args) throws Exception {                            
                ExcelRead ob=new ExcelRead();   
         String value=null;
                value=ob.ReadRow(1,1);
                System.out.println(op);
    }   
}

No comments:

Post a Comment