首页 > 代码库 > DataTable 导出 excel , 可以自定义列名,没有繁琐的引用

DataTable 导出 excel , 可以自定义列名,没有繁琐的引用

/// <summary>        /// 由DataTable导出Excel       /// </summary>       /// <param name="p"></param>       /// <param name="dt"></param>       /// <param name="fileName"></param>        /// <param name="b"> true为datatable列名  false为自定义列名</param>       /// <param name="colHeaders"> 自定义列名 已|分割</param>        public static void DataTableToExcel(Page p, DataTable dt, string fileName,bool b, string colHeaders)        {            HttpResponse resp;            resp = p.Response;            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");            resp.AppendHeader("Content-Disposition", "attachment;filename=" +  HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));            string  ls_item = "";            int cl = dt.Columns.Count;            ////定义表对象与行对象,同时用DataSet对其值进行初始化            //DataTable dt = ds.Tables[0];            DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的            int i = 0;                      //取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符            //取datatable里的列名            if (b)            {                for (i = 0; i < cl; i++)                {                    if (i == (cl - 1))//最后一列,加n                    {                        colHeaders += dt.Columns[i].Caption.ToString() + "\n";                    }                    else                    {                        colHeaders += dt.Columns[i].Caption.ToString() + "\t";                    }                }            }            else            {                string[] colHeaderList = colHeaders.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);                colHeaders = "";                //自定义列名                for (i = 0; i < colHeaderList.Length; i++)                {                    if (i == (colHeaderList.Length - 1))                    {                        colHeaders += colHeaderList[i] + "\n";                    }                    else                    {                        colHeaders += colHeaderList[i] + "\t";                    }                }            }            resp.Write(colHeaders);            //逐行处理数据             foreach (DataRow row in myRow)            {                               for (i = 0; i < cl; i++)                {                    if (i == (cl - 1))                    {                        ls_item += row[i].ToString() + "\n";                    }                    else                    {                        ls_item += row[i].ToString() + "\t";                    }                }                resp.Write(ls_item);                ls_item = "";            }            resp.End();        }

  

DataTable 导出 excel , 可以自定义列名,没有繁琐的引用