Write dymanic data to a new csv file using Selenium

1. Add this below dependency to pom.xml & rebuild.


2.Create a new class which is a utility for writing the values to csv file

package utils;

import com.aventstack.extentreports.Status;
import components.Config;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class WriteToCSV {

    private static WebDriver driver;

    private static final char DEFAULT_SEPARATOR = ',';

    public static void writeLine(Writer w, List<String> values) throws IOException {
        writeLine(w, values, DEFAULT_SEPARATOR, ' ');

    public static void writeLine(Writer w, List<String> values, char separators) throws IOException {
        writeLine(w, values, separators, ' ');

    private static String followCVSformat(String value) {

        String result = value;
        if (result.contains("\"")) {
            result = result.replace("\"", "\"\"");
        return result;

    public static void writeLine(Writer w, List<String> values, char separators, char customQuote) throws IOException {

        boolean first = true;

        //default customQuote is empty

        if (separators == ' ') {
            separators = DEFAULT_SEPARATOR;

        StringBuilder sb = new StringBuilder();
        for (String value : values) {
            if (!first) {
            if (customQuote == ' ') {
            } else {

            first = false;

3.Create a File Writer, add a location to save the generated csv file & Call the method like below.

// This is the default location of the csv file i.e Downloads folder 
fallback.put("downloads", new File("").getAbsolutePath() + "\\Downloads\\");

public static String getDownloads() {
        return config.getProperty("downloads");

    public static void setDownloads(String downloads) {
        config.put("downloads", downloads);

String csvFile = Config.getDownloads()+".csv";
FileWriter writer = new FileWriter(csvFile);
WriteToCSV.writeLine(writer, Arrays.asList("Header1","Header2","Header3"));
WriteToCSV.writeLine(writer, Arrays.asList(Data1,Data2,Data3));

4. Out put looks like below.


Leave a Reply

Fill in your details below or click an icon to log in:

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