ExcelResult继承:ViewResult(只支持excel版本2003及兼容2003的版本)通过视图模板生成excel
/// <summary> /// ms-excel视图 /// </summary> public class ExcelResult:ViewResult { #region 字段 private string _fileName; #endregion #region 构造函数 public ExcelResult(string fileName, object model) : this(null, fileName, model) { } public ExcelResult(string viewName, string fileName, object model) { this.ViewName = viewName; this.ViewData.Model = model; _fileName = fileName; } #endregion #region 重写方法 public override void ExecuteResult(ControllerContext context) { base.ExecuteResult(context); var response = context.HttpContext.Response; response.ContentType = "application/ms-excel"; response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); //response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); response.Charset = "utf-8"; response.Headers.Set("Content-Disposition", string.Format("attachment; filename={0}-{1:yyyy-MM-dd}.xls", _fileName, DateTime.Now)); } #endregion }
方法调用:
ActionResult 方法(){ return ExcelView("Exportinfo", "信息", cooperates.ToList());// cooperates.ToList()查询到的数据列表 }
视图页不用生成控制方法:
@model IEnumerable<Zhuoli.Model.BInfo> @{ Layout = null; } <table cellspacing="0" cellpadding="5" rules="all" border="1"> <thead> <tr> <th>编号</th> </tr> </thead> <tbody id="list-table-body"> @foreach (var item in Model) { <tr> @*编号*@ <td>@item.ID</td> </tr> } </tbody> </table>