How can we Import and Export CSV file in Selenium java

| | 2 min read

Reading or writing CSV file in Selenium Java can be done using a simple csv parser library called opencsv. Opencsv is free and is available under a commercial-friendly Apache 2.0 license. Opencsv contains classes to read and write csv files. For reading or writing csv files using Selenium, we need to import opencsv.jar to the java project.

Reading from CSV

Opencsv contains a CSVReader class to read data from CSV files from java code. For reading CSV line by line readNext() method can be used. readAll() method is available for reading full data. The advantage is that the delimiter can be specified while reading data from CSV. One thing to note is while using CSVReader to automate test scenarios the headers will not get automatically eliminated. So we need to either skip lines or need to specify the start line.

To list the data line by line, that is to display in an iterator style readNext() method should be used.

CSVReader readcsv = new CSVReader(new FileReader(“filepath/filename.csv”));
String [] nextLine;
while ((nextLine = readcsv.readNext())!= null) {
  System.out.println(nextLine[0]);
}

Here nextLine[] is an array of values from the line. If we want to list the whole data from the CSV file, readAll() method should be used.

CSVReader readcsv = new CSVReader(new FileReader(“filepath/filename.csv”));
List myData = readcsv.readAll();

Writing to CSV

Opencsv contains a class known as CSVWriter to write data into a CSV file. For writing CSV line by line writeNext() method can be used and for writing full data writeAll() method can be used. Both for reader and writer the default delimiter is comma, but we can specify other delimiters if required.

CSVWriter writecsv = new CSVWriter(new FileWriter("yourfile.csv"));
String[] username = " First name,Middle name,Last name");
writecsv.writeNext(name);
writecsv.close();

If the delimiter needs to be specified, then .split() should be used.

String[] username = "First name#Middle name#Last name".split('#'));

For writing data into a csv file we can also use FileWriter() method.

FileWriter writecsv = new FileWriter (“filepath/filename.csv”);
writecsv.append("First name,Middle name,Last name”);
writecsv.append('\n');

If you have included a CSV file in your Eclipse Java project, no need to give the entire file path. Only the file name is required .

Also, if you face any difficulties, please feel free to get in touch with us.