Sunday, 5 August 2012

ExportToExcel


using System;
using System.Web.UI.WebControls;
using System.Web;
using System.IO;
using System.Web.UI;

namespace GridViewExportExcel
{
    public class GridViewExport
    {
        //================================================================================
        // Method      : ExportToExcel
        // Description : This method remove all the link control before display to excel
        //================================================================================
        #region "Method ExportToExcel"
        public static void ExportToExcel(GridView _RptGrid, string _FileName)
        {
            try
            {
                HttpContext.Current.Response.Clear();                
                //change the file name at every saving           
                _FileName = _FileName + System.DateTime.Now.Millisecond.ToString();
                HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + _FileName + ".xls");
                HttpContext.Current.Response.ContentType = "application/ms-excel";
                using (StringWriter sw = new StringWriter())
                {
                    using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                    {
                        //  Create a form to contain the grid
                        Table table = new Table();
                        table.GridLines = GridLines.Both;
                        //  add the header row to the table
                        if (_RptGrid.HeaderRow != null)
                        {
                            PrepareControlForExport(_RptGrid.HeaderRow);
                            table.Rows.Add(_RptGrid.HeaderRow);
                        }

                        //  add each of the data rows to the table
                        foreach (GridViewRow row in _RptGrid.Rows)
                        {
                            PrepareControlForExport(row);
                            table.Rows.Add(row);
                        }

                        //  add the footer row to the table
                        if (_RptGrid.FooterRow != null)
                        {
                            PrepareControlForExport(_RptGrid.FooterRow);
                            table.Rows.Add(_RptGrid.FooterRow);
                        }

                        //  render the table into the htmlwriter
                        table.RenderControl(htw);

                        //  render the htmlwriter into the response
                        //  render the htmlwriter into the response
                        string _ResultHtml = sw.ToString();
                        _ResultHtml = _ResultHtml.Replace("<td", "<td align=right");
                        _ResultHtml = _ResultHtml.Replace(" – ", "-");
                        string _agent = String.Empty;
                        _agent = HttpContext.Current.Request.UserAgent;
                        // browser capabilities object                      
                        if (_agent.ToLower().Contains("chrome"))
                        {
                            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                            // You can set this header here thanks to the Response.Buffer = true above
                            // This header fixes the Google Chrome bug
                            HttpContext.Current.Response.AddHeader("Content-Length", encoding.GetBytes(_ResultHtml).ToString());
                        }
                        HttpContext.Current.Response.Write(_ResultHtml);
                        HttpContext.Current.Response.Flush();
                        HttpContext.Current.Response.Close();

                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        //================================================================================
        // Method      : PrepareControlForExport
        // Description : This method remove all the link control before display to excel
        //================================================================================
        #region "Method Preparecontrol"
        private static 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);
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
                }
                else if (current is ImageButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
                }
                else if (current is HyperLink)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
                }
                else if (current is DropDownList)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
                }
                else if (current is CheckBox)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
                }

                if (current.HasControls())
                {
                    PrepareControlForExport(current);
                }
            }
        }
        #endregion
    }
}

No comments:

Post a Comment