How to Read CSV Files in Selenium


What is CSV file ?
A CSV is a comma separated values file, which allows data to be saved in a table structured format. CSVs look like a garden-variety spreadsheet but with a .csv extension.We can use it in NotePad/Excel …..
Here i am using opencsv Jar to read the data.
It’s really simple to read the data from CSV files if we follow the below steps.

Step 1 : Download opencsv from Click here to download OpenCsv

Step 2 : Extract it and add the opencsv Jar under your Project BuildPath.

Step 3 : Here I am attaching the sample file.Sample CSV file

Step 4 : Execute the below code

import java.io.FileReader;

import org.testng.annotations.Test;

import au.com.bytecode.opencsv.CSVReader;

public class ReadCsv {

private static final String FILE_PATH=”F:/test.xls”;

@Test
public void test() throws Exception {
CSVReader reader = new CSVReader(new FileReader(FILE_PATH));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
System.out.println(“Value 1 : [” + nextLine[0] + “]\nValue 2 : [” + nextLine[1] + “]\nValue 3 :[” + nextLine[2] + “]\nValue 4 :[” + nextLine[3] + “]”);

}
}

Its Done !!! Now use this according to your requirements.
}

Advertisements

2 thoughts on “How to Read CSV Files in Selenium

  1. viki goyal July 29, 2018 / 8:08 am

    I am new to Selenium Webdriver Testng and trying to Develop Data Driven framework using CSVReader

    I have 5 tests in Testng and have to run those all on different environments. So basically I have to pick a different url and client, but other pages, elements remain same.

    My Question is, Where do I put while loop so that it reads first line and execute all the tests and then read second line and so on.

    I tried initialize CSV reader at class level, before suite, before method etc. but it throws error, it works for a particular test if I am putting insside @Test but that doesn’t resolve the purpose, I couldn’t find any relevant answer on the internet.

    Like

    • Hari Charan August 20, 2018 / 12:04 am

      Does it solve if we use multiple hooks with a priority flag?

      Like

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s