导出数据生成Excel(MVC)

时间:2024-10-02 22:36:56

/// <summary>
/// 生成Excel
/// </summary>
/// <returns></returns>
public FileResult ExportProductInfo()
{
List<Aniuge_spu> spuList = ProductBusiness.GetInstance().GetProdutInfo();
StringBuilder sb = new StringBuilder();
sb.Append("<table border='1'cellspacing='0' cellpadding='0'>");
sb.Append("<tr>");
List<string> list = new List<string> { "编号", "名称", "形状" };
//第一行
foreach (var item in list)
{
sb.AppendFormat("<td style='font-size:14px;text-align:center;'>{0}</td>", item);
}
//获取的参数列表绑定
foreach (var item in spuList)
{
sb.Append("<tr>");
sb.AppendFormat("<td>{0}</td>", item.Code);
sb.AppendFormat("<td>{0}</td>", item.Name);
sb.AppendFormat("<td>{0}</td>", item.Shape);
sb.Append("</tr>");
}
sb.Append("</table>");

byte[] fileContents = Encoding.Default.GetBytes(sb.ToString());
//下载
return File(fileContents, "application/ms-excel", "streams.xls");
}