Skip to main content

How to Export Grid Data To Excel and Doc file Format

Hello Friends

                               


I am going to explain how to export grid view to Word or Excel document using asp.net.

I have one grid view that has filled with user details now I need to export grid view data to word or excel document based on selection. To implement this functionality first we need to design aspx page like this 

<asp:ImageButton ID="btnExcel" runat="server" ImageUrl="~/ExcelImage.jpg" OnClick="btnExportExcel_Click" />
        <asp:ImageButton ID="btnWord" runat="server" ImageUrl="~/WordImage.jpg" OnClick="btnWord_Click" />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Font-Names="Arial"
            Font-Size="11pt" AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="green"
            AllowPaging="True" OnPageIndexChanging="OnPaging" CellPadding="4" ForeColor="#333333"
            GridLines="None">
            <AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
            <Columns>
                <asp:TemplateField>
                    <HeaderTemplate>
                        <asp:CheckBox ID="chkCol0" runat="server" Checked="true" />
                        <asp:Label ID="lblCol0" runat="server" Text="CustomerID" />
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblCustomerID" runat="server" Text='<%# Eval("CustomerID")%>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <HeaderTemplate>
                        <asp:CheckBox ID="chkCol1" runat="server" Checked="true" />
                        <asp:Label ID="lblCol1" runat="server" Text="ContactName" />
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblContactName" runat="server" Text='<%# Eval("ContactName")%>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <HeaderTemplate>
                        <asp:CheckBox ID="chkCol2" runat="server" Checked="true" />
                        <asp:Label ID="lblCol2" runat="server" Text="City"></asp:Label>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblCity" runat="server" Text='<%# Eval("City")%>' />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <EditRowStyle BackColor="#2461BF" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White"></HeaderStyle>
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#EFF3FB" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F5F7FB" />
            <SortedAscendingHeaderStyle BackColor="#6D95E1" />
            <SortedDescendingCellStyle BackColor="#E9EBEF" />
            <SortedDescendingHeaderStyle BackColor="#4870BE" />
        </asp:GridView>


On code behind write

Write three functions
1)  To bind grid
2)  To export to excel
3) To export to Doc

Bind Grid Function

private void BindGrid()
{
    string strQuery = "select CustomerID,City,ContactName" +
        " from customers";
    DataTable dt = new DataTable();
    String strConnString = System.Configuration.ConfigurationManager
                .ConnectionStrings["conString"].ConnectionString;
    SqlConnection con = new SqlConnection(strConnString);
    SqlDataAdapter sda = new SqlDataAdapter();
    SqlCommand cmd = new SqlCommand(strQuery);
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    try
    {
        con.Open();
        sda.SelectCommand = cmd;
        sda.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        con.Close();
        sda.Dispose();
        con.Dispose();
    }
}

To export to excel Function

protected void btnExportExcel_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
  
    Response.AddHeader("content-disposition",
     "attachment;filename=GridViewExport.xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);

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

    GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
    GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
    GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
    GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");

    ArrayList arr = (ArrayList)ViewState["States"];
    GridView1.HeaderRow.Cells[0].Visible = Convert.ToBoolean(arr[0]);
    GridView1.HeaderRow.Cells[1].Visible = Convert.ToBoolean(arr[1]);
    GridView1.HeaderRow.Cells[2].Visible = Convert.ToBoolean(arr[2]);

    GridView1.HeaderRow.Cells[0].FindControl("chkCol0").Visible = false;
    GridView1.HeaderRow.Cells[1].FindControl("chkCol1").Visible = false;
    GridView1.HeaderRow.Cells[2].FindControl("chkCol2").Visible = false;

    for (int i = 0; i < GridView1.Rows.Count;i++ )
    {
        GridViewRow row = GridView1.Rows[i];
        row.Cells[0].Visible = Convert.ToBoolean(arr[0]);
        row.Cells[1].Visible = Convert.ToBoolean(arr[1]);
        row.Cells[2].Visible = Convert.ToBoolean(arr[2]);  
        row.BackColor = System.Drawing.Color.White;
        row.Attributes.Add("class", "textmode");
        if (i % 2 != 0)
        {
            row.Cells[0].Style.Add("background-color", "#C2D69B");
            row.Cells[1].Style.Add("background-color", "#C2D69B");
            row.Cells[2].Style.Add("background-color", "#C2D69B");
        }
    }
    GridView1.RenderControl(hw);
    string style = @"<style> .textmode { mso-number-format:\@; } </style>";
    Response.Write(style);
    Response.Output.Write(sw.ToString());
    Response.End();
}


Export to doc Function

protected void btnWord_Click(object sender, ImageClickEventArgs e)
{
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    Response.ClearContent();
    Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.doc"));
    Response.Charset = "";
    Response.ContentType = "application/ms-word";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    GridView1.RenderControl(htw);
    Response.Write(sw.ToString());
    Response.End();
}

Common Error
There might be some common error like which may occur while coding

Resolution

Put this method in code behind

public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }
You can download complete from this link Download Code




Comments