DataGrid to CSV file

13,476

I used this Snippet to export a DataGrid To CSV. Maybe it helps:

public void OnExportGridToCSV(object sender, System.EventArgs e)
{
    // Create the CSV file to which grid data will be exported.
    StreamWriter sw = new StreamWriter(Server.MapPath("~/GridData.csv"), false);
    // First we will write the headers.
    DataTable dt = ((DataSet)grid1.DataSource).Tables[0];

    int iColCount = dt.Columns.Count;
    for (int i = 0; i < iColCount; i++)
    {
        sw.Write(dt.Columns[i]);
        if (i < iColCount - 1)
        {
            sw.Write(",");
        }
    }
    sw.Write(sw.NewLine);
    // Now write all the rows.
    foreach (DataRow dr in dt.Rows)
    {
        for (int i = 0; i < iColCount; i++)
        {
            if (!Convert.IsDBNull(dr[i]))
            {
                sw.Write(dr[i].ToString());
            }
            if (i < iColCount - 1)
            {
                sw.Write(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator);
            }
        }
        sw.Write(sw.NewLine);
    }
    sw.Close();
}
Share:
13,476
Marc Uberstein
Author by

Marc Uberstein

Founder of Guinea Pixel | Playing Together http://guinea-pixel.com

Updated on June 04, 2022

Comments

  • Marc Uberstein
    Marc Uberstein almost 2 years

    I am binding a DataTable to a DataGrid, everything is working fine. My next step is to export the DataGrid data to a CSV file, comma delimited.

    What is the best/easiest way doing this with ASP.Net 3.5?

  • Kingpin
    Kingpin over 12 years
    Oh, one thank. Use System.Globalization.CultureInfo.CurrentCulture.TextInfo.Lis‌​tSeparator to get the right ListSeparator. We here in europe use semicolon :)
  • Petr Hruzek
    Petr Hruzek over 8 years
    If fields contain ,(;) or " your CSV file will be malformed.