asp.net 导出EXCEL

代码
/// <summary>
/// 导出Excel
/// </summary>
protected void btnExcel_Click(object sender, EventArgs e)
{
string fileName = "文件名";
Page.Response.Clear();
Page.Response.Buffer
= true;
Page.Response.Charset
= "GB2312";
Page.Response.AppendHeader(
"Content-Disposition", "attachment;filename=" + Server.UrlPathEncode(fileName) + ".xls");
Page.Response.ContentEncoding
= System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
Page.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
Page.EnableViewState = false;
Page.Response.Write(getExcelHtml());
//获取导出内容
Page.Response.End();
}
/// <summary>
/// 返回导出Excel的内容,以HTML格式显示方式导出
/// </summary>
private string getExcelHtml()
{

DataTable dt
= //获取数据集
string headHtml = "<thead><tr style='background-color:#BBB;'><th>名称</th><th>数量</th</tr></thead>";
string totalHtml = "";
StringBuilder sbHtml
= new StringBuilder();
sbHtml.Append(
"<tbody>");
foreach (DataRow row in dt.Rows)
{
sbHtml.Append(
"<tr><td>" + row["Name"] + "</td><td>" + row["Number"] + "</td></tr>");

}
string bodyhtml = sbHtml.ToString() + "</tbody>";
string html = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"1\">" + headHtml + bodyhtml + totalHtml + "</table>";
return html;
}
原文地址:https://www.cnblogs.com/554006164/p/1902050.html