Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export gridview data into CSV file

I have a gridview control in ASP.Net 2.0 and i need to export this gridview data into CSV file.

I have bind this gridview with the dataset.After binding the dataset to the gridview i have done some changes in the gridview data like if I got 0 in dataset then i show 0 as "Started" in the gridview and if i got 1 in the dataset then I show 1 as "Not Started" in the gridview.

So, i can't use dataset directly for exporting. What i need is..i want the code (in c#) that export my gridview data(not dataset's data) into CSV file.

like image 794
jitendra Avatar asked Jul 13 '11 05:07

jitendra


1 Answers

First thanks to Devjosh for the good answer which I modified to work with gridviews that have AutoGenerateColumns=true and AllowSorting=true. Plus I stripped out any returned commas from the data to make sure csv file was not corrupted.

private void ExportReport()
{
    // set the resulting file attachment name to the name of the report...
    string fileName = "test";

    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".csv");
    Response.Charset = "";
    Response.ContentType = "application/text";

    System.Text.StringBuilder sb = new System.Text.StringBuilder();

    // Get the header row text form the sortable columns
    LinkButton headerLink = new LinkButton();
    string headerText = string.Empty;

    for (int k = 0; k < gvReport.HeaderRow.Cells.Count; k++)
    {
        //add separator
        headerLink = gvReport.HeaderRow.Cells[k].Controls[0] as LinkButton;
        headerText = headerLink.Text;
        sb.Append(headerText + ",");
    }
    //append new line
    sb.Append("\r\n");
    for (int i = 0; i < gvReport.Rows.Count; i++)
    {
        for (int k = 0; k < gvReport.HeaderRow.Cells.Count; k++)
        {
            //add separator and strip "," values from returned content...

            sb.Append(gvReport.Rows[i].Cells[k].Text.Replace(",", "") + ",");
        }
        //append new line
        sb.Append("\r\n");
    }
    Response.Output.Write(sb.ToString());
    Response.Flush();
    Response.End();
}
like image 83
zach.xtr Avatar answered Sep 28 '22 02:09

zach.xtr