DataTable 데이터를 Excel로 내보내기

5659 단어 Datatable
DataTable 유형의 데이터가 있으면 Excel로 내보낼 수 있습니다.
     public static void ExportToExcel(DataTable dt, string fileName)

        {

            string outputFileName = null;  

            string browser = HttpContext.Current.Request.UserAgent.ToUpper();  

  

            // 。 IE , FF 。

            if (browser.Contains("MS") == true && browser.Contains("IE") == true)

                outputFileName = HttpUtility.UrlEncode(fileName);  //%e5%90%8d%e5%8d%95

            else if (browser.Contains("FIREFOX") == true)  

                outputFileName = "\"" + fileName + ".xls\"";  //" .xls" 

            else  

                outputFileName = HttpUtility.UrlEncode(fileName);



            HttpResponse Response = HttpContext.Current.Response;



            Response.ClearContent();

            Response.AddHeader("content-disposition", "attachment; filename=" + outputFileName + ".xls");

            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");

            Response.Charset = "gb2312";

            Response.ContentType = "application/ms-excel";



            string tab = "";

            foreach (DataColumn dc in dt.Columns)

            {

                HttpContext.Current.Response.Write(tab + dc.ColumnName);

                tab = "\t";

            }

            HttpContext.Current.Response.Write("
"); int i; foreach (DataRow dr in dt.Rows) { tab = ""; for (i = 0; i < dt.Columns.Count; i++) { HttpContext.Current.Response.Write(tab + dr[i].ToString()); tab = "\t"; } HttpContext.Current.Response.Write("
"); } HttpContext.Current.Response.End(); }

좋은 웹페이지 즐겨찾기