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">
     <ItemTemplate>
         <asp:ImageButton ID="btnDownload"runat="server"ImageUrl="~/images/icon_excel.png"OnClick="btnDownload_click"ToolTip="Download Excel File" />
     </ItemTemplate>
     </asp:TemplateField>




Step 2: In the code behind file add the following code:
protected voidbtnDownload_click(object sender, ImageClickEventArgs e)
    {
        con.Open();
        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();
        adp.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            ExportToSpreadsheet(dt, "DataFile");
        }
        con.Close();

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

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

        context.Response.Write(Environment.NewLine);

        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.Write(Environment.NewLine);
        }
        context.Response.Buffer = true;
        context.Response.ContentType = "application/vnd.ms-excel";
        context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".xls");
        context.Response.End();
    }
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 http://asp.net-informations.com/excel/asp-excel-export.htm asp.net excel export in c# and vb.net

    ling

    ReplyDelete