原贴地址1:https://www.cnblogs.com/weihengblogs/p/3437278.html
原贴地址2:https://blog.csdn.net/LIAO_Love/article/details/75007422
原贴地址3:https://blog.csdn.net/weixin_42353499/article/details/80522734
以下方法测试可用:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
/// <summary>
/// ExcelHelper 的摘要说明
/// </summary>
public class ExcelHelper
{
public static void CreateExcel_t(DataTable dt, string FileName)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentType = "application/vnd.ms-xls";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + FileName + ".xls");
StringBuilder table = new StringBuilder();
table.Append("<table border='1'>");
table.Append("<tr>");
for (int i = 0; i < dt.Columns.Count; i++)
{
table.Append("<td><b>");
table.Append(dt.Columns[i].Caption.ToString());//表格的标题
table.Append("</b></td>");
}
table.Append("</tr>");
for (int i = 0; i < dt.Rows.Count; i++)
{
table.Append("<tr>");
for (int j = 0; j < dt.Columns.Count; j++)
{
table.Append("<td style='vnd.ms-excel.numberformat:@'>");
table.Append(dt.Rows[i][j].ToString());
table.Append("</td>");
}
table.Append("</tr>");
}
table.Append("</table>");
HttpContext.Current.Response.Write(table);
HttpContext.Current.Response.End();
}
}
调用方法:
protected void btnExcel_Click(object sender, EventArgs e)
{
DataTable dt = GetData();
ExcelHelper.CreateExcel_t(dt, "产品列表_" + DateTime.Now.ToString("yyyyMMddHHmmss"));
}