Monday, June 3, 2013

How to Export Grid View Record as an Excel File in ASP.Net

1 comment
In this tutorial we will see how to export each single record as an Excel File in Grid View Control. In this example I will  just list the code of downloading each gridview record as and Excel file. You can Get the whole code of Saving Records into database and binding to Grid View from my previous example or you can modify the code according to your requirement.

Steps to Export Each GridView Record as an Excel File:

Step 1: Add a template field inside the grid view design view as shown below:
<asp:TemplateField HeaderText="Download File" ItemStyle-HorizontalAlign="Center">
         <asp:ImageButton ID="btnDownload"runat="server"ImageUrl="~/images/icon_excel.png"OnClick="btnDownload_click"ToolTip="Download Excel File" />

Step 2: In the code behind file add the following code:
protected voidbtnDownload_click(object sender, ImageClickEventArgs e)
        ImageButton btnDetail = sender as ImageButton;
        GridViewRow gvrow = (GridViewRow)btnDetail.NamingContainer;
        hdid.Value = Convert.ToString(GridView1.DataKeys[gvrow.RowIndex].Value);
        string qry2 = "Select STU_NAME, CLASS, EMAIL from Student_Record where STU_ID=" + hdid.Value + "";
        SqlDataAdapter adp = newSqlDataAdapter(qry2, con);
        DataTable dt = newDataTable();
        if (dt.Rows.Count > 0)
            ExportToSpreadsheet(dt, "DataFile");

    public static void ExportToSpreadsheet(DataTabletable, string name)
        HttpContext context = HttpContext.Current;

        foreach (DataColumncolumn in table.Columns)
            context.Response.Write(column.ColumnName + "\t");


        foreach (DataRowrow in table.Rows)
            for (int i = 0; i < table.Columns.Count; i++)
                context.Response.Write(row[i].ToString().Replace(";", string.Empty) + "\t");
        context.Response.Buffer = true;
        context.Response.ContentType = "application/";
        context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".xls");
Now run the application to view the final result.
You can modify the database record fetching query(qry2) above in code according to your table and the records shown in the grid view.
If you get any problem during implementing the code then let us know through comments.

1 comment:

  1. Export to excel excel export in c# and