Labels

Monday, January 20, 2014

Export from GridView to Excel

Following function exports your GridView data to Excel. It has full support for unicode characters.



///
        /// Grid to Excel with Custom FileName.
        ///
        ///
        ///
        ///
        public static void GridToExcel(HttpResponse response, System.Web.UI.WebControls.GridView gv, string filename)
        {

            response.Clear();
            ContentDisposition cd = new ContentDisposition
            {
                Inline = false,
                FileName = filename + "_" + DateTime.Now.ToString().Replace(" ", "_").Replace("/", "_").Replace(":", "_").Replace("-", "_") + ".xls"
            };

            response.AddHeader("content-disposition", cd.ToString());

            // If you want the option to open the Excel file without saving than
            // comment out the line below
            // Response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.ContentType = "application/ms-excel";
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
            System.Web.UI.HtmlControls.HtmlForm hform = new System.Web.UI.HtmlControls.HtmlForm();
            gv.Parent.Controls.Add(hform);
            hform.Attributes["runat"] = "server";
            hform.Controls.Add(gv);
            hform.RenderControl(htmlWrite);
            response.Write("");
            response.Write("
"
+ filename + "
");
            response.Write("
Date : "
+ DateTime.Now.ToLongDateString() + "
");
            response.Write(stringWrite.ToString());
            response.End();
        }
       

        ///
        /// Grid to Excel with Custom FileName and Custom Header.
        ///
        ///
        ///
        ///
        ///
        public static void GridToExcel(HttpResponse response, System.Web.UI.WebControls.GridView gv, string filename, string header)
        {

            response.Clear();
            ContentDisposition cd = new ContentDisposition
            {
                Inline = false,
                FileName = filename + "_" + DateTime.Now.ToString().Replace(" ", "_").Replace("/", "_").Replace(":", "_").Replace("-", "_") + ".xls"
            };
            response.Charset = "UTF-8";
            response.AddHeader("content-disposition", cd.ToString());

            // If you want the option to open the Excel file without saving than
            // comment out the line below
            // Response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.ContentType = "application/ms-excel";
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
            System.Web.UI.HtmlControls.HtmlForm hform = new System.Web.UI.HtmlControls.HtmlForm();
            gv.Parent.Controls.Add(hform);
            hform.Attributes["runat"] = "server";
            hform.Controls.Add(gv);
            hform.RenderControl(htmlWrite);
            response.Write("");
            response.Write("
"
+ header + "
");
            response.Write("
Date : "
+ DateTime.Now.ToLongDateString() + "
");
            response.Write(stringWrite.ToString());
            response.End();
        }

Add Column Number at first row of Grid

Following function adds column number at first row in your datatable.



        public static void AddColumnNumberInGrid(DataSet ds, int startColumnIndex)
        {
            object[] cols = new object[ds.Tables[0].Columns.Count];
            for (int i = 0; i < cols.Length; i++)
            {
                if (i >= startColumnIndex)
                {
                    cols[i] = (i + 1 - startColumnIndex).ToString();
                }
                else
                {
                    //cols[i] = String.Empty;
                }

            }

            DataRow row = ds.Tables[0].NewRow();
            row.ItemArray = cols;
            ds.Tables[0].Rows.InsertAt(row, 0);
            ds.AcceptChanges();
        }


Serialize Datatable using JavaScriptSerializer


        public static string JavaScriptSerialize(DataTable dt)
        {
            JavaScriptSerializer ser = new JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            return ser.Serialize(rows);
        }