Wednesday, April 07, 2010

GridView Export from ASP.NET

Common method for Exporting gird content 

#region Methods : ExportGridView & PrepareControlForExport
    /// <summary>
    /// Purpose : To Export GridView in Excel format.
    /// </summary>
    /// <param name="strFileName">Execl File name</param>
    /// <param name="gv">Grid View</param>
    /// <param name="isRemove">If false, wont check the remove column</param>
    /// <param name="arrayList">List of columns to hide {1,2,3}</param>
    /// <param name="removeColumn">Column to remove</param>
    public void ExportGridView(string strFileName, GridView gv, bool isRemove, ArrayList arrayList)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader(
            "content-disposition", string.Format("attachment; filename={0}", strFileName));
        HttpContext.Current.Response.ContentType = "application/ms-excel";

        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        Table tableExport = new Table();
        // Setting line borders to the exported grid
        tableExport.GridLines = GridLines.Both;

        if (isRemove == false)
        {
            if (gv.HeaderRow != null)
            {
                this.PrepareControlForExport(gv.HeaderRow);
                tableExport.Rows.Add(gv.HeaderRow);
            }
            foreach (GridViewRow row in gv.Rows)
            {
                this.PrepareControlForExport(row);
                tableExport.Rows.Add(row);
            }
            if (gv.FooterRow != null)
            {
                this.PrepareControlForExport(gv.FooterRow);
                tableExport.Rows.Add(gv.FooterRow);
            }

        }
        else
        {
            if (arrayList.Count > 0)
            {
                    if (gv.HeaderRow != null)
                    {
                        this.PrepareControlForExport(gv.HeaderRow);
                        tableExport.Rows.Add(gv.HeaderRow);
                        for (int removeColumn = 0; removeColumn < arrayList.Count; removeColumn++)
                        {
                            gv.HeaderRow.Cells.Remove(gv.HeaderRow.Cells[Int32.Parse(arrayList[removeColumn].ToString())]);
                        }
                    }
                    foreach (GridViewRow row in gv.Rows)
                    {
                        this.PrepareControlForExport(row);
                        for (int removeColumn = 0; removeColumn < arrayList.Count; removeColumn++)
                        {
                            row.Cells.Remove(row.Cells[Int32.Parse(arrayList[removeColumn].ToString())]);
                        }
                        tableExport.Rows.Add(row);
                    }
                    if (gv.FooterRow != null)
                    {
                        this.PrepareControlForExport(gv.FooterRow);
                        tableExport.Rows.Add(gv.FooterRow);
                        for (int removeColumn = 0; removeColumn < arrayList.Count; removeColumn++)
                        {
                            gv.FooterRow.Cells.Remove(gv.FooterRow.Cells[Int32.Parse(arrayList[removeColumn].ToString())]);
                        }
                    }
            }
        }

        tableExport.RenderControl(htw);
        HttpContext.Current.Response.Write(sw.ToString().Trim());
        HttpContext.Current.Response.End();

    }

    /// <summary>
    /// Prepaing the control for export
    /// Customize your controls depening on your logic    ///
    /// </summary>
    /// <param name="control"></param>
    private void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is LinkButton)
            {
                control.Controls.Remove(current);
                if ((current as LinkButton).Style["display"] != "none" && (current as LinkButton).Visible)
                {
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text.Trim()));
                }
            }
            else if (current is ImageButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText.Trim()));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text.Trim()));
            }
            else if (current is DropDownList)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text.Trim()));
            }
            else if (current is CheckBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            }
            else if (current is HtmlAnchor)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HtmlAnchor).InnerText.Trim()));
            }
            else if (current is Label)
            {
                control.Controls.Remove(current);
                if ((current as Label).Style["display"] != "none" && (current as Label).Visible)
                {
                    control.Controls.AddAt(i, new LiteralControl((current as Label).Text.Trim()));
                }
            }

            if (current.HasControls())
            {
                this.PrepareControlForExport(current);
            }
        }
    }
    #endregion Methods : ExportGridView & PrepareControlForExport

 

Sample code to call code behind

   ArrayList list = new ArrayList();
            DraftsGridView.AllowPaging = false;
            BindDrafts("StartDateTime", ASCENDING);
         // Add list of columns that are to be hidden. If you not need any columns
        //then just send list object without adding any and set the third parameter to false
            list.Add(3);
            common.ExportGridView("Drafts.xls", DraftsGridView, true, list);

No comments:

Post a Comment