DataTable 的数据导出到 Excel

如果有个DataTable类型的数据,可以这样导出到Excel中:

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("\n");

            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("\n");
            }
            HttpContext.Current.Response.End();
        }
DataTable 的数据导出到 Excel

DataTable 的数据导出到 Excel

上一篇:索引图片和alpha通道图片


下一篇:获取机器安装.NET版本的几种方式