Export GridView data to CSV file

Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=SearchResults.csv");
Response.Charset = "";

Response.ContentType = "application/text";

gvSearchResutls.AllowPaging = false;

//Bind DataTable to GridView

//Search() method returns a DataTable of search results

gvSearchResutls.DataSource = Search();
gvSearchResutls.DataBind();

//String builder class to add row data
StringBuilder sb = new StringBuilder();

for (int k = 0; k < gvSearchResutls.Columns.Count; k++)
{

    //add separator

    sb.Append(gvSearchResutls.Columns[k].HeaderText + ',');

}

append new line

sb.Append("\r\n");
Get Rows
for (int i = 0; i < gvSearchResutls.Rows.Count; i++)
{
    //Get columns
    for (int k = 0; k < gvSearchResutls.Columns.Count; k++)
    {

        //add separator
        sb.Append(gvSearchResutls.Rows[i].Cells[k].Text + ',');

    }

    //append new line

    sb.Append("\r\n");

}

Response.Output.Write(sb.ToString());

Response.Flush();

Response.End();

References:

http://www.aspsnippets.com/

http://www.victorchen.info/export-datatable-to-csv-file-download-in-c/

7 Comments

  • How about if a csv file WITHOUT HEADER??
    please help me.
    thnx

  • rkvedul@gmail.com said:

    iam getting the csv files with only column names but not with rows values plss help me

    Hi

    Please post your source code.

  • Hi Zarek,

    I am not a good web designer I am afraid. Note that this site is the results of Microsoft provided weblogs.

    I choose templates and add content, choose the images.
    Hope it helps you!
    In order to get free CSS templates, check
    http://www.freecsstemplates.org/
    http://www.csszengarden.com/

  • I had some problems with my application skipping out of both of your FOR loops when you use the gvSearchResults.Rows.Count. Instead, I had to use "gvSearchResults.Rows[0].Cells.Count" in order to get an integer that would work with my loops. Obviously this took some validation to make sure at least one row was returned, but it this worked for me.

    (also, you spelled results as resutls)

    Thanks for the post though - pointed me in the right direction!

  • Hi Joshc1107,

    Thanks for your comment. I think you mean to say 'gvSearchResults.Columns.Count' instead of gvSearchResults.Rows.Count.

    Note that when you set GridView AutoGenerateColumns="True" in aspx, GridView.Column.Count always returns '0'. When you set AutoGenerateColumns="False" and declare columns exclusively, GridView.Columns.Count returns number of columns.
    =====================================================






    ======================================================
    Yes, there is typo, but the code works fine without any problems where GridView columns are specified as shown above.

  • sir, your blog is blossoming

  • Great thanks!! It is actually what I need.

Comments have been disabled for this content.