C# 将datatable导出成Excel


public void Result( )
{

try
{
StringBuilder sql = new StringBuilder();
List parameters = new List();

sql.Append(@"sql 查询语句");
DataTable dt = DbHelperSQL.Query(sql.ToString()).Tables[0];
StringBuilder TableHead = new StringBuilder();
StringBuilder TableFoot = new StringBuilder();
TableHead.Append("")
.Append("")
.Append("");
TableFoot.Append("导出时间:" + DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss") + "");
DataTableToExcel(dt, TableHead.ToString(), TableFoot.ToString(), name + "汇总_" + DateTime.Now.ToString("yyyyMM"));

}
catch (Exception ex)
{

}
}

///


/// DataTable导出Excel
///

/// 集合
/// 表头
/// 文件名称
public static void DataTableToExcel(DataTable data, string ChartHead, string ChartFoot, string fileName)
{
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
HttpContext.Current.Response.Charset = "Utf-8";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName + ".xls", Encoding.UTF8));
StringBuilder sbHtml = new StringBuilder();
sbHtml.AppendLine("");
sbHtml.AppendLine("");
//写出表头
sbHtml.AppendLine(ChartHead);
string NumberAsTextExp = "vnd.ms-excel.numberformat:@";
//写数据
foreach (DataRow row in data.Rows)
{
sbHtml.Append("");
for (int i = 0; i < row.ItemArray.Count(); i++)
{
if (row[i].GetType() == typeof(string))
{
sbHtml.Append("");
}
else
{
sbHtml.Append("");
}
}
sbHtml.AppendLine("");
}
//写汇总行
sbHtml.AppendLine(ChartFoot);
sbHtml.AppendLine("
").Append(row[i]).Append("").Append(row[i]).Append("
");
HttpContext.Current.Response.Write(sbHtml.ToString());
HttpContext.Current.Response.End();
}