How do you read data from Excel?
Archana Ramchandra Nale
Empowering 2000+ Job Seekers to Land Their Dream Jobs | Expert in Referrals, Profile Optimization & Real-Time Job Updates | LinkedIn & Naukri Profile Specialist | Placement Assistance & Mock Interviews
To read data from an Excel file in Selenium with Java, you can use the Apache POI library, which provides excellent support for handling Excel files in Java applications. Here’s a detailed guide with an example to help you get started:
Step-by-Step Guide to Reading Data from Excel in Selenium with Java
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
Username --> Password
user1 --> pass1
user2 --> pass2
Below is a sample code snippet to read data from an Excel file using Apache POI:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelReader {
public static void main(String[] args) throws IOException {
// Path to the Excel file
String filePath = "path/to/TestData.xlsx";
FileInputStream file = new FileInputStream(filePath);
// Create Workbook instance for XLSX file
Workbook workbook = new XSSFWorkbook(file);
// Get the sheet at index 0 (first sheet)
Sheet sheet = workbook.getSheetAt(0);
// Loop through all rows in the sheet
for (int i = 1; i <= sheet.getLastRowNum(); i++) { // Assuming row 0 has headers
Row row = sheet.getRow(i);
// Get cell values for each column in the row
String username = row.getCell(0).getStringCellValue();
String password = row.getCell(1).getStringCellValue();
// Output the values
System.out.println("Username: " + username + ", Password: " + password);
// Here you can use the values in your Selenium test scripts
// Example: driver.findElement(By.id("username")).sendKeys(username);
// driver.findElement(By.id("password")).sendKeys(password);
}
// Close workbook and file
workbook.close();
file.close();
}
}
In this code:
Example Output
If your Excel file has two rows of data (excluding the header), the output should look like this:
Username: user1, Password: pass1
Username: user2, Password: pass2
Additional Tips
Our Services
If you’re interested in further advancing your automation testing skills or seeking career opportunities, we offer the following services through Your Corporate Life:
For more details or to avail of our services, connect with us on WhatsApp: https://wa.me/c/919156951085. Let us help you achieve your career goals!