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

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s