Writing Test Results into Excel Files in Selenium
Writing test results into Excel files in Selenium is a common requirement in automation frameworks, especially for reporting and logging test outcomes. This is usually done using Apache POI (for Java) or openpyxl / pandas (for Python).
Below, I’ll guide you through how to write Selenium test results into Excel files using both Java and Python.
✅ Java (Using Apache POI)
Step 1: Add Apache POI Dependencies (Maven)
<dependencies>
<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>8
</dependency>
</dependencies>
Step 2: Write Results into Excel
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
public class WriteTestResults {
public static void main(String[] args) throws IOException {
String filePath = "TestResults.xlsx";
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Results");
// Headers
Row header = sheet.createRow(0);
header.createCell(0).setCellValue("Test Case");
header.createCell(1).setCellValue("Status");
// Sample Test Results
String[][] data = {
{"Login Test", "Passed"},
{"Search Test", "Failed"},
{"Logout Test", "Passed"}
};
for (int i = 0; i < data.length; i++) {
Row row = sheet.createRow(i + 1);
row.createCell(0).setCellValue(data[i][0]);
row.createCell(1).setCellValue(data[i][1]);
}
// Write to file
FileOutputStream fileOut = new FileOutputStream(filePath);
workbook.write(fileOut);
fileOut.close();
workbook.close();
System.out.println("Test Results Written to Excel!");
}
}
✅ Python (Using openpyxl)
Step 1: Install openpyxl
pip install openpyxl
Step 2: Write Results into Excel
from openpyxl import Workbook
# Create workbook and sheet
wb = Workbook()
ws = wb.active
ws.title = "Test Results"
# Headers
ws.append(["Test Case", "Status"])
# Sample Test Results
results = [
("Login Test", "Passed"),
("Search Test", "Failed"),
("Logout Test", "Passed"),
]
# Add results
for test_case, status in results:
ws.append([test_case, status])
# Save file
wb.save("test_results.xlsx")
print("Test Results Written to Excel!")
π‘ Tips for Real-World Selenium Projects
Integrate writing to Excel inside your TestNG (Java) or pytest (Python) hooks (e.g., @AfterMethod, yield teardown).
Use timestamps or test IDs for better tracking.
Optionally color-code passed/failed rows using Apache POI styles or openpyxl.styles.
Would you like an example integrated with Selenium test code as well?
Learn Selenium JAVA Course in Hyderabad
Read More
Reading Test Data from Excel using Apache POI
π Data Handling and Advanced Concepts
How to Create a Base Test Class in Java
Reusable Methods in Java for Selenium Tests
Visit Our IHUB Talent Training in Hyderabad
Comments
Post a Comment