首页 > 代码库 > DataTable导出为Excel

DataTable导出为Excel

/// <summary>
        /// 导出Excel Datatable版本
        /// </summary>
        /// <param name="dt">导出的Datatable</param>
        /// <param name="ExcelName">导出EXCEL的名称 不需要要带有扩展名_xls</param>
        public static void NewExportExcelScore(DataTable dt, string Title, string colHeaders, int cl)
        {
            HttpResponse resp = System.Web.HttpContext.Current.Response;
            string ExcelName = Title + DateTime.Now.ToString("yyyyMMddHHmmss");
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + ExcelName + ".xls");
            string ls_item = "";
            DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
            int i = 0;
            //int cl = dt.Columns.Count;
            //取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符
            resp.Write("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body><table border=1><tr style=\" Gray 1px solid;text-align:center\">");
            //for (i = 0; i < cl; i++)
            //{
            //    colHeaders += "<th>" + dt.Columns[i].Caption.ToString() + "</th>";
            //}
            resp.Write(colHeaders + "</tr>");
            //向HTTP输出流中写入取得的数据信息
            //逐行处理数据
            foreach (DataRow row in myRow)
            {
                //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据  
                ls_item = "<tr bgcolor=#ABCDC1>";
                for (i = 0; i < cl; i++)
                {
                    if (i == (cl - 1))//最后一列,加n
                    {
                        ls_item += "<td>" + row[i].ToString() + "</td></tr>";
                    }
                    else
                    {
                        if (i == 2)
                        {
                            ls_item += "<td style=‘vnd.ms-excel.numberformat:@‘>" + " " + row[i].ToString() + "</td>";//到处后已字符形式显示
                        }
                        else
                        {
                            ls_item += "<td>" + row[i].ToString() + "</td>";
                        }
                    }
                }
                resp.Write(ls_item);
            }
            resp.Write("</table></body></html>");
            resp.End();
        }

 

DataTable导出为Excel