Monday, February 1, 2010

Export gridview data to excel and word


Every software has a common requirement to export data to Microsoft Excel or Word format. I saw multiple on this topic in asp.net forum.  Here I will explain a simple way of exporting your gridview data to excel (.xls) or word (.doc) format when used with master page and updatepanel.  
Firstly we will write html codes:



<table style="width: 100%;">
                                    <tr>
                                        <td>
                                            <asp:Label ID="Label3" runat="server" Text="Export to: "></asp:Label>
                                            <asp:LinkButton ID="lnkExportToExcel" runat="server"
                                                OnClick="lnkExportToExcel_Click">Excel</asp:LinkButton>
                                            &nbsp;<asp:LinkButton ID="lnkExportToWord" runat="server"
                                                onclick="lnkExportToWord_Click">Word</asp:LinkButton>
                                            &nbsp;<asp:DropDownList ID="ddlExportOption" runat="server">
                                                <asp:ListItem Value="0">This Page</asp:ListItem>
                                                <asp:ListItem Value="1">All Page</asp:ListItem>
                                            </asp:DropDownList>
                                            &nbsp;</td>
                                    </tr>
                                </table>
Code behind:
Now we will write lnkExportToExcel and lnkExportToWord click event handler code:
protected void lnkExportToExcel_Click(object sender, EventArgs e)
        {
            if (ddlExportOption.SelectedIndex == 0)
            {
                Helper.Export("excel", gvHrEmploye, this.Page);
            }
            else
            {
                int pageNo = gvHrEmploye.PageIndex;
                gvHrEmploye.AllowPaging = false;
                BindList();
                Helper.Export("excel", gvHrEmploye, this.Page);
                gvHrEmploye.AllowPaging = true;
                gvHrEmploye.PageIndex = pageNo;
                BindList();
            }
        }

protected void lnkExportToWord_Click(object sender, EventArgs e)
        {
            if (ddlExportOption.SelectedIndex == 0)
            {
                Helper.Export("word", gvHrEmploye, this.Page);
            }
            else
            {
                int pageNo = gvHrEmploye.PageIndex;
                gvHrEmploye.AllowPaging = false;
                BindList();
                Helper.Export("word", gvHrEmploye, this.Page);
                gvHrEmploye.AllowPaging = true;
                gvHrEmploye.PageIndex = pageNo;
                BindList();
            }
        }


Here notice that we are currently displaying data or all data based on users choice.


Then we will look at export method which actually does the job:
public static void Export(string type, GridView gv, Page page)
    {
        if (type == "excel")
        {
            page.Response.AddHeader("content-disposition", "attachment;filename=EmployeeList.xls");
            page.Response.ContentType = "application/vnd.xls";
        }
        else if (type == "word")
        {
            page.Response.AddHeader("content-disposition", "attachment;filename=EmployeeList.doc");
            page.Response.ContentType = "application/msword";
        }
        page.Response.Charset = String.Empty;
        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
        gv.RenderControl(hw);
        page.Response.Write(sw.ToString());
        page.Response.End();
    }
You can use this code to export gridview data to excel and word format. This method works fine when working with pages that does not have update panel and have no master page. But when used with master page and update panel it gives an error while executing RenderControl()method.
Error:
"Control of type GridView must be placed inside form tag with runat = server"
To solve this error you have to override VerifyRenderingInServerForm method:
public override void VerifyRenderingInServerForm(Control control)
        {
            return;
        }
This method confirms that HtmlForm control is rendered for specified ASP.Net server control at runtime.
If you run this time you will get another error:
RegisterForEventValidation can only be called during Render()


To solve this problem add EnableEventValidation = "false" page tag of .aspx page.
<%@ Page Language="C#" MasterPageFile="~/Master/MasterPage.master" AutoEventWireup="true"
    MaintainScrollPositionOnPostback="true" CodeFile="HrEmployeeForm.aspx.cs" Inherits="ERP.Web.UI.HrEmployeeForm"
    EnableEventValidation="false" %>


This time your code should work properly. Have a nice feature working properly in your asp.net application. Thanks.