Testng Code to Read Data From Csv File
A CSV (Comma Separated Values) file is a text based format that represents the data typically found in a spreadsheet or a database tabular array.
Information technology is a common format for information interchange as it is simple, compact, and used everywhere. It will open up into Excel with a double click, and most all databases have a tool to allow import from CSV. It is also readily parseable with simple code.
The basic format is defined by rows of column information. Each row is terminated by a newline to begin the next row. Within the row, each column is distinguished by a comma.
Information within each cavalcade can exist double-quoted to escape embedded commas in the data. Embedded double quotes are escaped with a pair of double-quote characters.
CSV files are likewise called apartment files, equally CSV files comprise only simple formatted 2 Dimensional tables. As well, y'all practise not need sophisticated software to handle CSV. You demand a elementary text editor to manipulate the CSV files.
We can handle the CSV file using the below packages :
- Apache Commons CSV
- Open up CV
Read and Write Excel with Apache POI
First of all, you demand to add an apache-commons-csv dependency in your project. If you apply 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>
For Jar file, please go to : https://commons.apache.org/proper/commons-csv/download_csv.cgi, download the goose egg/tar.gz file under binaries section and add the jar into eclipse with External Jars.
Please relieve the below CSV content in your local system with .csv extension.
CSV file without header
Name,Product,Clarification karthiQ,chercher tech,tutorial larry folio,google,search engine gates,microsoft,operating system
CSV file with a header
karthiQ,chercher tech,tutorial larry page,google,search engine gates,microsoft,operating system Handle Nested frames in Selenium
We can read the CSV file using Apache Commons CSV packages; there could be two kinds of CSV files.
- CSV file with Header
- CSV file without Header
In this Program, I will exist using the CSV file without header, follow below steps to read the CSV file using Apache Commons CSV packet.
Steps to Read CSV file :
1. Create the CSV file and store it in your local machine.
ii. Create a new BufferReader object, using the Files form and pass the above CSV file equally a parameter.
// read the file Reader reader = Files.newBufferedReader(Paths.go(CSV_File_Path));
iii. At present All the details are stored in the BufferReader object. To parse the BufferReader object into comma-separated values, nosotros have to create an object for CSV parser. We have to laissez passer what we are going to parse, and what is the delimiter for parsing (separator)
// parse the file into csv values CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);
four. Now all the information is loaded into CSVparse object similar a table like rows and columns; at present, we have to iterate over every row nowadays in information technology. We tin can access the cavalcade using the index, along with get() method
for (CSVRecord csvRecord : csvParser) { // Accessing Values past Column Alphabetize String name = csvRecord.get(0); String production = csvRecord.get(1); String clarification = csvRecord.get(two); Consummate programme for reading CSV file with cavalcade alphabetize
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 coffee.nio.file.Files; import java.nio.file.Paths; public class ApacheCommonsCSV { @Examination public void readCSV() throws IOException { String CSV_File_Path = "C:UsersuserDesktopq.csv"; // read the file Reader reader = Files.newBufferedReader(Paths.become(CSV_File_Path)); // parse the file into csv values CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT); for (CSVRecord csvRecord : csvParser) { // Accessing Values by Cavalcade Alphabetize Cord proper noun = csvRecord.get(0); String product = csvRecord.go(1); String description = csvRecord.get(2); // print the value to console System.out.println("Tape No - " + csvRecord.getRecordNumber()); System.out.println("---------------"); System.out.println("Proper name : " + name); Arrangement.out.println("Product : " + product); Organisation.out.println("Description : " + description); Organization.out.println("--------------- "); } } } Read and Write Property files in Selenium
In the higher up example, we take seen how to read the CSV file with an alphabetize of the column, but when we read like that, we may not become the verbal information what row we are reading.
To arrive more readable, we should create it with column names and then that we can call the values by its cavalcade name.
We have to create headers to phone call the values with its proper noun; We tin set the header while creating the CSVParser.
For this case, I am using a CSV file without a header.
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT .withHeader("Proper name", "Product", "Description") .withIgnoreHeaderCase() .withTrim());
Complete programme for reading CSV file with Column Names.
public class ReadWithColumnName { @Examination 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 cavalcade String proper name = csvRecord.go("Name"); String product = csvRecord.get("Product"); String clarification = csvRecord.get("Description"); System.out.println("Record No - " + csvRecord.getRecordNumber()); Organisation.out.println("---------------"); Organisation.out.println("Proper name : " + name); Organization.out.println("Product : " + product); Organisation.out.println("Description : " + description); System.out.println("--------------- "); } } } Running TestNG from CMD
In the final example, we have seen how to create Column names for the CSV files, but most of the time CSV files exercise come with headers .
When we have headers in the CSV file, nosotros may demand to convert them into column names, or we have to tell the CSV parse that this fils has Headers.
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT .withFirstRecordAsHeader() .withIgnoreHeaderCase() .withTrim());
Consummate programme for reading CSV files with headers
public class CSVWithHeader { @Test public void readCSV() throws IOException { Cord CSV_File_Path = "C:UsersuserDesktopq_header.csv"; // read the file Reader reader = Files.newBufferedReader(Paths.get(CSV_File_Path)); CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT .withFirstRecordAsHeader() .withIgnoreHeaderCase() .withTrim()); for (CSVRecord csvRecord : csvParser) { // Accessing values by the names assigned to each column String name = csvRecord.get("Name"); String production = csvRecord.get("Production"); String description = csvRecord.get("Description"); Arrangement.out.println("Record No - " + csvRecord.getRecordNumber()); System.out.println("---------------"); Organization.out.println("Name : " + proper noun); System.out.println("Production : " + production); System.out.println("Clarification : " + description); Organization.out.println("--------------- "); } } } Robot Class in Selenium
Sometimes we may need to create the CSV files based on the values present in the website
Steps to Create a CSV file :
1. Create the BufferedWriter object for the file to which we are going to write our content. This file may or may not exist in the File organization.
If File exists in the file arrangement, so information technology will be replaced, if the file is not present, then the new file will be created with the given name.
Cord CSV_File_Path = "C:UsersuserDesktopq1.csv"; // writer BufferedWriter author = Files.newBufferedWriter(Paths.get(CSV_File_Path));
2. Create the object for the CSVPrinter form and also specify what is the delimiter and headers of the file.
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT .withHeader("ID", "Proper name", "Designation", "Company"));
3. Using the printRecord method, you can button the values into the file.
csvPrinter.printRecord("1", "karthiq", "admin", "chercher tech");
4. The flush() method pushes the file and its content into the local system. Complete program for writing the data into CSV files
import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.testng.annotations.Examination; public class WriteCSV { @Examination public void writeCSVFileTest() throws IOException { String CSV_File_Path = "C:UsersuserDesktopq1.csv"; BufferedWriter writer = Files.newBufferedWriter(Paths.get(CSV_File_Path)); CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT .withHeader("ID", "Name", "Designation", "Company")); csvPrinter.printRecord("1", "karthiq", "admin", "chercher tech"); csvPrinter.printRecord("ii", "Jeff", "CEO", "Amazon"); csvPrinter.printRecord("iii", "Tim", "CEO", "Apple tree"); csvPrinter.affluent(); csvPrinter.close(); } } Listeners in Selenium
public course ConvertExcelToCSV { public static void xls(File inputFile, File outputFile) { // For storing information into CSV files StringBuffer data = new StringBuffer(); endeavor { FileOutputStream fos = new FileOutputStream(outputFile); // Go the workbook object for XLS file HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(inputFile)); // Become beginning sheet from the workbook HSSFSheet sheet = workbook.getSheetAt(0); Cell prison cell; Row row; // Iterate through each rows from kickoff canvas Iterator rowIterator = sail.iterator(); while (rowIterator.hasNext()) { row = rowIterator.side by side(); // For each row, iterate through each columns Iterator cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { jail cell = cellIterator.adjacent(); switch (cell.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: data.suspend(cell.getBooleanCellValue() + ","); pause; case Jail cell.CELL_TYPE_NUMERIC: data.append(cell.getNumericCellValue() + ","); break; case Cell.CELL_TYPE_STRING: information.suspend(cell.getStringCellValue() + ","); intermission; example Cell.CELL_TYPE_BLANK: data.append("" + ","); interruption; default: data.append(jail cell + ","); } } data.append(' '); } fos.write(data.toString().getBytes()); fos.shut(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void chief(String[] args) { File inputFile = new File("data.xls"); File outputFile = new File("input.csv"); xls(inputFile, outputFile); } } Compare Dropdown values
Near Author :
I am Pavankumar, Having 8.5 years of feel currently working in Video/Live Analytics projection.
Source: https://chercher.tech/java/csv
0 Response to "Testng Code to Read Data From Csv File"
Post a Comment