Monday 12 August 2013

Generate excel from datatable



 public static void ExportGridView(string fileName, DataTable A_objData)
        {
            try
            {
                DataTable objDataTable = A_objData;
                string attachment = string.Format("attachment; filename={0}", fileName);
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.AddHeader("content-disposition", attachment);
                HttpContext.Current.Response.ContentType = "application/ms-excel";
                System.Text.StringBuilder strOrderList = new System.Text.StringBuilder(1000);
                string strTest = "";
                int iColumnCount = A_objData.Columns.Count;
                for (int iIndex = 0; iIndex < iColumnCount; iIndex++)
                    strTest = strTest + objDataTable.Columns[iIndex].ToString() + "\t";
                strTest = strTest + "\n";
                strOrderList.Append(strTest);

                foreach (DataRow rows in objDataTable.Rows)
                {
                    strOrderList.Append(GetTabSeperatedString(rows, iColumnCount));
                }
                byte[] info = new System.Text.UTF8Encoding(true).GetBytes(strOrderList.ToString());

                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.ClearHeaders();
                HttpContext.Current.Response.ContentType = "application/ms-excel";
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
                HttpContext.Current.Response.BinaryWrite(info);
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private static string GetTabSeperatedString(DataRow A_objDataTableRow, int A_iColumnCount)
        {
            string strRowValue = "";
            string strColumnValue = "";

            for (int iIndex = 0; iIndex < A_iColumnCount; iIndex++)
            {
                strColumnValue = A_objDataTableRow[iIndex].ToString();
                strColumnValue = strColumnValue.Replace("\n", " ");
                strColumnValue = strColumnValue.Replace("\r", " ");
                strColumnValue = strColumnValue.Replace("\t", " ");
                if (strColumnValue == "&nbsp;")
                    strColumnValue = " ";
                strRowValue += strColumnValue + "\t";
            }
            strRowValue += "\n";
            return strRowValue;
        }

No comments:

Post a Comment