Mike Johnston
Mike Johnston

Reputation: 233

Writing to existing CSV or Excel File in Visual Studio C#

I want to be able to continually update a CSV or Excel xlsx file, maybe using NPOI or anything else really. I just need to accomplish the below.

Example of my code is below, I am capturing timings. The code is using Selenium. Each time the test is run, I need those timings to be exported to an existing excel/csv file that I will have stored on my C: drive. I dont want to overwrite existing cells, instead I want to add the new timings on the next blank row each time.

My existing excel file, will have just 3 header columns. These will be titled "Date Of Test", "Name of Test", "Elapsed Time"

        [Test]
    public void TimeForWebPagesToLoad()
    {
        IWebDriver driver = new FirefoxDriver();

        DateTime currentDateTime = DateTime.Now;
        var dateTime = currentDate.ToString();

        var sw1 = Stopwatch.StartNew();
        driver.Navigate().GoToUrl("http://www.google.com");
        sw1.Stop();
        Console.WriteLine("Time for Google to load is {0}", sw1.Elapsed);

        var sw2 = Stopwatch.StartNew();
        driver.Navigate().GoToUrl("http://www.facebook.com");
        sw2.Stop();
        Console.WriteLine("Time for Facebook to load is {0}", sw2.Elapsed);

        /*TODO code to write the Elapsed time into excel
        WriteToExcelMethod(dateTime, "Google Perf Test", sw1.Elapsed)
        WriteToExcelMethod(dateTime, "Facebook Perf Test", sw2.Elapsed)
        */

        Assert.IsTrue(sw1.Elapsed < TimeSpan.FromSeconds(10));
        Assert.IsTrue(sw2.Elapsed < TimeSpan.FromSeconds(10));

    }

Upvotes: 1

Views: 2256

Answers (3)

Harshit Gindra
Harshit Gindra

Reputation: 365

You can also use File Class Here is a small snippet which can be used

        var csv = new StringBuilder();

        var newLine = string.Format("{0},{1},{2}", firstValue, secondValue, thirdValue);
        csv.AppendLine(newLine);

        File.AppendAllText(fileUrl, csv.ToString());

I hope this should work for you.

Upvotes: 0

Vlad Feinstein
Vlad Feinstein

Reputation: 11311

Something like that would work:

public static void WriteToExcelMethod(DateTime dt, string str, TimeSpan ts)
{
    string path = @"c:\temp\MyTest.csv";
    string line = String.Format(@"""{0}"",""{1}"",""{2}""", dt, str, ts);
    using (StreamWriter sw = File.AppendText(path))
    {
        sw.WriteLine(line);
    }
}

Upvotes: 1

Tinwor
Tinwor

Reputation: 7973

Using CSV file:

    using (StreamWriter sw = new StreamWriter("pippo.csv", true))
    {
        sw.WriteLine(string.Format("{0};{1};{2}", DateTime.Now, "Google Perf Test", ws1.Elapsed));
        sw.WriteLine(string.Format("{0};{1};{2}", DateTime.Now, "Facebook Perf Test", ws2.Elapsed));
    }

Upvotes: 0

Related Questions