CSV Files with selenium
I. Concept CSV file
It is a common format for data interchange as it is simple, compact, and used everywhere. It will open into Excel with a double click, and nearly all databases have a tool to allow import from CSV
It is a common format for data interchange as it is simple, compact, and used everywhere. It will open into Excel with a double click, and nearly all databases have a tool to allow import from CSV
We can handle the CSV file using the below packages :
- Apache Commons CSV
- Open CV
II. Dependency CSV Integration
First of all, you need to add an apache-commons-csv dependency in your project. If you use maven, then add the following dependency to your pom.xml file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.5</version>
</dependency>
Link: https://commons.apache.org/proper/commons-csv/download_csv.cgi
III. Reading a CSV file by Column Index
Ex:
import org.testng.annotations.Test;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ApacheCommonsCSV {
@Test
public void readCSV() throws IOException {
String CSV_File_Path = "C:UsersuserDesktopq.csv";
// read the file
Reader reader = Files.newBufferedReader(Paths.get(CSV_File_Path));
// parse the file into csv values
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);
for (CSVRecord csvRecord : csvParser) {
// Accessing Values by Column Index
String name = csvRecord.get(0);
String product = csvRecord.get(1);
String description = csvRecord.get(2);
// print the value to console
System.out.println("Record No - " + csvRecord.getRecordNumber());
System.out.println("---------------");
System.out.println("Name : " + name);
System.out.println("Product : " + product);
System.out.println("Description : " + description);
System.out.println("---------------
");
}
}
}
IV. Reading a CSV file with Column Name
Ex:
public class ReadWithColumnName {
@Test
public void readCSV() throws IOException {
String CSV_File_Path = "C:UsersuserDesktopq.csv";
// read the file
Reader reader = Files.newBufferedReader(Paths.get(CSV_File_Path));
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT
.withHeader("Name", "Product", "Description")
.withIgnoreHeaderCase()
.withTrim());
for (CSVRecord csvRecord : csvParser) {
// Accessing values by the names assigned to each column
String name = csvRecord.get("Name");
String product = csvRecord.get("Product");
String description = csvRecord.get("Description");
System.out.println("Record No - " + csvRecord.getRecordNumber());
System.out.println("---------------");
System.out.println("Name : " + name);
System.out.println("Product : " + product);
System.out.println("Description : " + description);
System.out.println("---------------
");
}
}
}