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)
{
    try
    {
        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);
        objWrite.Write(dataToWrite);
        objWrite.Close();
    }
    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.