Learn Selenium and Java for Selenium

Saturday, 21 May 2016

Reading a Excel File using Apache POI


Author : Ashwini Velapure (Test Automation Engineer) https://www.linkedin.com/in/ashwinivelapure

Steps to Read the Excel File

  • Specify the Location of File
  • Load WorkBook
  • Load Sheet: Sheet can be loaded via getSheetAt() method , sheet name /index can be passed as argument.By default Sheet1 has zero index and so on
  • Load Cell: There are 2 methods offered by XSSFSheet class , one is get row() and the other is get Cell() ,the row number and the column number are passed as an argument respectively
  • Read Data
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.IOException;  
 import java.util.Iterator;  
 import org.apache.poi.ss.usermodel.Row;  
 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 ReadFile {  
      public static void main(String[] args) throws IOException {  
           // TODO Auto-generated method stub  
           FileInputStream file = new FileInputStream(new File("C:\\Users\\Ashish Banka\\Downloads\\Test1.xlsx"));  
           XSSFWorkbook workbook = new XSSFWorkbook(file);    
           XSSFSheet sheet = workbook.getSheetAt(0); //Read Sheet 1,   
           String S= sheet.getRow(0).getCell(0).getStringCellValue();  
           System.out.println(S);  
      }  
 }  

Notes

1-Eclipse support one forward slash or two backward slash ,so we have used two backword slash in order to locate the file
2- XSSFWorkbook is a class so we have created one reference variable "workbook" in order to access the method of this class which is getSheetAt()
3- As we know XSSFWorkbook is a class, its object can be created via new XSSFWorkbook(File)
4-getStringCellValue () method return a string value of Cell so we have stored in a string called "s"

Output


Output of Excel File displaying Row 0 and Column 0 value

Excel Sheet


Excel File used for Reading


0 comments:

Post a Comment

Popular Posts

Recent Posts



Newsletter

Join our newsletter to get secret tips directly in your inbox!


*We Hate Spam!

Powered by Blogger.