How To Get Data From File To Script
This article will focus on how to read data from an Excel file in Selenium WebDriver using Java. We need Apache POI libraries to perform such operations.
Apache POI Installation:
Step 1 – Download the Apache POI jar file from the official website and click on the Download section. One can download the Binary Distribution zip file.
Step 2 – Once the zip file is downloaded, extract it and save it.
Step 3 – In Eclipse, Right click on Project --> Build Path --> Configure Build Path --> Library --> Add External JARs and add all jar files from all the folders from apache unzipped file.
Read Data from Excel File in Selenium:
1) Get file location by creating FileInputStream object.
FileInputStream file = new FileInputStream("Path of Excel File\\FileName.xlsx");
2) We use WorkbookFactory class and its Create method to get object of Workbook interface, in that we pass file as a argument.
Workbook wb = WorkbookFactory.create(file);
3) To enter in to sheet we call getSheet() method which returns Sheet interface.
Sheet sheet = wb.getSheet("SheetName");
4) To get String value we use getStringCellValue() Method of Cell interface
String value = sheet.getRow(i).getCell(j).getStringCellValue();
OR We can write this all things in one line
String value = WorkbookFactory.create(file).getSheet("SheetName").getRow(0).getCell(0).getStringCellValue();
CODE
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ReadExcelSheet {
public static void main(String[] args) throws EncryptedDocumentException, IOException {
FileInputStream file = new FileInputStream("D:\\Automation\\Username_Password.xlsx");
Workbook wb = WorkbookFactory.create(file);
Sheet sheet = wb.getSheet("LoginDetail");
// for data in 2nd index row and 0th index cell value
String value = sheet.getRow(2).getCell(0).getStringCellValue();
System.out.println(value);