12

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.

Jay Riggs
  • 53,046
  • 9
  • 139
  • 151
jitendra
  • 567
  • 4
  • 11
  • 17

3 Answers3

31

Try following code, i used it already many times. It will export the data directly from gridview to csv file specified in the code.

protected void btnExportCSV_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition",
     "attachment;filename=GridViewExport.csv");
    Response.Charset = "";
    Response.ContentType = "application/text";

    GridView1.AllowPaging = false;
    GridView1.DataBind();

    StringBuilder sb = new StringBuilder();
    for (int k = 0; k < GridView1.Columns.Count; k++)
    {
        //add separator
        sb.Append(GridView1.Columns[k].HeaderText + ',');
    }
    //append new line
    sb.Append("\r\n");
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        for (int k = 0; k < GridView1.Columns.Count; k++)
        {
            //add separator
            sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
        }
        //append new line
        sb.Append("\r\n");
    }
    Response.Output.Write(sb.ToString());
    Response.Flush();
    Response.End();
}

for more information visit Here Hope it will help you

Devjosh
  • 6,450
  • 4
  • 39
  • 61
  • 3
    Thanks,I tried this but only get header columns name not the data in these columns. – jitendra Jul 13 '11 at 07:12
  • for (int i = 0; i < GridView1.Rows.Count; i++) { for (int k = 0; k < GridView1.Columns.Count; k++) { //add separator sb.Append(GridView1.Rows[i].Cells[k].Text + ','); } //append new line sb.Append("\r\n"); } particularly this portion will get you the rows trace this code while running – Devjosh Jul 13 '11 at 08:25
  • i got the column count greater than 0 but same problem i didn't got row count greater than 0. – jitendra Jul 14 '11 at 07:07
  • are you able to fill your girdview because if there are rows in your gridview then for (int i = 0; i < GridView1.Rows.Count; i++) should not return a 0 value ideally it must be greater – Devjosh Jul 14 '11 at 08:54
  • 1
    Had problems with no data in the output. Remove the following lines `GridView1.AllowPaging = false; GridView1.DataBind();` It then worked great! Thanks for the post. – Donald Gullett Jul 04 '12 at 21:46
  • I get Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. – Welsh King Nov 07 '12 at 14:50
  • when do you get that error ? are you using updatepanel. i would suggest you debug code line by line. – Devjosh Nov 07 '12 at 14:55
  • thanks, yeah i solved it by adding the following to PageLOAD ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page); scriptManager.RegisterPostBackControl(CtrlExportCSV.FindControl("btnExport")); – Welsh King Nov 07 '12 at 15:10
  • @Devjosh thanks for sharing this, but I really can't get it to work. I run the code within my button click event, but it seems that nothing happens. When I debug everything seems ok and no errors. Any pointers? In which directory does your code put GridViewExport.csv? – U r s u s Dec 03 '14 at 12:17
  • Thanks for getting back to me @Devjosh. It doesn't. My grid is inside an update panel. Is that a problem? – U r s u s Dec 03 '14 at 12:33
  • @Dura is your button in the updatepanel and you defined triggers for it ? – Devjosh Dec 03 '14 at 16:57
  • @Dura please read this link for the issue you are facing http://stackoverflow.com/questions/3909973/response-object-not-returning-excel-stream-in-update-panel – Devjosh Dec 03 '14 at 16:59
  • @Devjosh thanks! Adding the trigger helped, but I can only get the columns headers and no rows. I've followed the suggestion above and got rid of `GridView1.AllowPaging = false;GridView1.DataBind();` but no joy. Do you have any other suggestion? thanks a lot. – U r s u s Dec 04 '14 at 10:07
  • @dura , if you can post your code in a new question providing a link to the question here, may be i can help – Devjosh Dec 05 '14 at 04:43
  • @Devjosh here's my [new question](http://stackoverflow.com/questions/27315951/gridview-empty-rows-when-exporting-to-csv) – U r s u s Dec 05 '14 at 12:32
5

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();
}
zach.xtr
  • 51
  • 1
  • 1
-1
private void ExportGridToCSV()
        {            
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=Employee.csv");
            Response.Charset = "";
            Response.ContentType = "application/text";
            GridEmployee.AllowPaging = false;
            GridEmployee.DataBind();

            StringBuilder columnbind = new StringBuilder();
            for (int k = 0; k < GridEmployee.Columns.Count; k++)
            {

                columnbind.Append(GridEmployee.Columns[k].HeaderText + ',');
            }

            columnbind.Append("\r\n");
            for (int i = 0; i < GridEmployee.Rows.Count; i++)
            {
                for (int k = 0; k < GridEmployee.Columns.Count; k++)
                {

                    columnbind.Append(GridEmployee.Rows[i].Cells[k].Text + ',');
                }

                columnbind.Append("\r\n");
            }
            Response.Output.Write(columnbind.ToString());
            Response.Flush();
            Response.End();

        }

Just call this method in a button Click event. For more Code, click the link Export gridview data into CSV file

I hope this helps you. Thanks.

Arun Kumar
  • 159
  • 1
  • 6