接着上面的来,继续导出Execl 的功能
使用FileResult 方式直接可以生产Execl ,这样我们将会写大量处理后台的代码,个人感觉不好,只是展示出来,提供参考
第一步:编辑控制器
public FileResult ExportFile()
{
var list = GetList(); var sbHtml = new StringBuilder();
string title = "order";
//标题
sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0'>");
sbHtml.Append("<tr>");
sbHtml.AppendFormat("<td style='font-size: 14px;text-align:center; font-weight:bold;' height='30' colspan='3'>{0}</td>", title);
sbHtml.Append("</tr>");
sbHtml.Append("</table>");
sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0' style='font-size: 12px;'>");
var lstTitle = new List<string> { "Year", "Week", "Date" }; //编写表头
sbHtml.Append("<tr>");
foreach (var item in lstTitle)
{
sbHtml.AppendFormat("<td style='text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item);
}
sbHtml.Append("</tr>");
int i = ; var strDataType = string.Empty;
var strQuestion = string.Empty; foreach (var item in list)
{ sbHtml.Append("</tr>");
sbHtml.AppendFormat("<td align='center'>{0}</td><td align='center'>{1}</td><td align='center'>{2}</td>", item.Id, item.Name,item.CreateTime.ToString("yyyy-MM-dd hh:mm:ss") );
sbHtml.Append("</tr>");
i++; }
sbHtml.Append("</table>"); byte[] fileContents = Encoding.Default.GetBytes(sbHtml.ToString()); string fileName = title + ".xls"; if (Request.Browser.Browser == "IE")
{
Response.Charset = "GB2312";
Response.ContentEncoding = Encoding.GetEncoding("GB2312");
Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", HttpUtility.UrlEncode(fileName, Encoding.UTF8)));
}
return File(fileContents, "application/ms-excel", fileName);
}
第二步:前端调用
function ExportFile() { window.open("/Home/ExportFile"); }
OK ,这样就好 控制器里面的代码也是挺简单,自己看看吧