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.

Client for Excel in the Windows Store

We would like to share with you our new application for work with Excel documents.

Client for Excel – App for convenient Work with Excel documents!

Are you tired of searching of the application that allows you to work with Excel documents on your Windows 8.1 device? – You just need to try the new Client for Excel.

Client for Excel is designed specifically to work with .xls and .xlsx files.

Using this app you can view, create, edit, and delete Excel documents very easy.

User-friendly interface allows you to create Tables Excel, fill various reports and edit your documents without much effort.

In addition, Client for Excel has a modern design, and the development team of this program is gonna improve its functionality.

Enjoy working with documents with Client for Excel!

Features

  • View and create documents in formats .xls, .xlsx.
  • Fully compatible with Microsoft Excel.
  • Support of formulas (basic formulas are added on the panel: Sum, Average, Count Numbers, Max, Min).
  • Ability to copy / paste, moving the cell, area, rows, columns.
  • Delete the contents of the columns, rows, cells; remove sheets.
  • Ability to merge cells.
  • Formatting a document:
  • Sort the contents of the sheet
  • Support for different fonts
  • Change the text size and color of text and background
  • Alignment of the text on the vertical and horizontal directions
  • Underline, bold, italic text
  • The allocation of boundaries
  • Full support of the touch.
  • Print and Print to PDF.

Client for Excel in the Windows Store http://apps.microsoft.com/windows/app/client-for-xls/7cb0b5c4-410c-4374-a0dd-7042c5230cce