Write DataGrid to CSV file in WPF app

This post shows how to write a DataGrid in WPF to a CSV file. We will export the data contained in the DataGrid along with the column headers to a CSV file. Here’s how it can be done.

Step 1: Build a CSV string from the DataGrid

Use the following method to convert a DataGrid to a CSV string.

public static string DataTable2CSV(DataGrid table, string separator=",")
    object[,] data = table.PrepareData();
    StringBuilder builder = new StringBuilder(Convert.ToString((char)65279));

    for (int k = 0; k < data.GetLength(0); k++)
        List<string> tempList = new List<string>();
        for (int l = 0; l < data.GetLength(1); l++)
            tempList.Add(data[k, l].ToString());
        builder.Append(string.Join(separator, tempList)).Append(Environment.NewLine);
    return builder.ToString();

The method accepts a DataGrid name as a parameter and converts it to a comma separated string value.

Step 2: Write the String to a Excel file.

Next write the above generated string to a excel file. The function WriteToXls takes the string to be written as an input and writes its to a excel file. It actually writes a CSV file which is saved with an .xlsx extension. It will open as an Excel file.

private string WriteToXls(string dataToWrite)
        string destination = DateTime.Now.ToString("dd_MM_yyyy_HH_mm") + LotNumber;
        foreach (char c in System.IO.Path.GetInvalidFileNameChars())
            destination = destination.Replace(c, '_');
        destination = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + destination + ".xlsx";
        FileStream fs = new FileStream(destination, FileMode.Create, FileAccess.Write);
        StreamWriter objWrite = new StreamWriter(fs);
    catch (Exception ex)
        return null;

Step 3: Use the above Methods to write to CSV

Here’s how you can use the above functions to write to CSV.

WriteToXls(DataTable2CSV(myDataGrid, ","));

Note: myDataGrid is the name of the DataGrid present in your XAML page.

Vivek Maskara

I am pursuing BTech in Software Engineering from Delhi Technological University. I develop apps, create websites and blog about my app experiences.

Read more:
How to create your first Windows Phone app
How to change the App name and Tile name of your Windows phone app
Data binding in Windows Phone app – One way binding