使用MVC 3导出Excel数据

我一直在寻找互联网的天,我只是想知道如果有人已经做了任何使用MVC 3出口数据excel的工作。我真的需要一个很好的教程,有分步说明如何导出Excel数据使用MVC 3与C#。 我发现了大量的文章,但没有一篇似乎与我现有的数据库工作。 我只是在寻找一些方法的指示等。本教程http://stephenwalther.com/blog/archive/2008/06/16/asp-net-mvc-tip-2-create-a-custom- action-result-that-returns-microsoft-excel-documents.aspx似乎强烈build议在堆栈溢出。 我已经按照文章的指示信,但我不能运行该程序,因为Visual Studio方法GenerateExcel1返回时抛出一个错误

这是VS说我有一个错误

return this.Excel(db, db.iamp_mapping, "data.xls")

现在我得到2个错误消息说

错误1'DBFirstMVC.Controllers.PaController'不包含'Excel'的定义和最好的扩展方法重载'DBFirstMVC.CustomActionResults.ExcelControllerExtensions.Excel(System.Web.Mvc.Controller,System.Data.Linq.DataContext,System .Linq.IQueryable,string)'有一些无效参数C:\ Documents and Settings \ lk230343 \ My Documents \ Visual Studio 2010 \ WebSites \ DBFirstMVC Saves \ DBFirstMVC_CRUD_and_PAGING_done \ DBFirstMVC \ Controllers \ PaController.cs 193 24 DBFirstMVC

错误2参数2:无法从'DBFirstMVC.Models.PaEntities'转换为'System.Data.Linq.DataContext'C:\ Documents and Settings \ lk230343 \ My Documents \ Visual Studio 2010 \ WebSites \ DBFirstMVC Saves \ DBFirstMVC_CRUD_and_PAGING_done \ DBFirstMVC \控制器\ PaController.cs 193 35 DBFirstMVC

有没有人见过这些错误之前,或有任何想法,我可以如何解决它们? 我的意思是excel方法存在于ExcelControllerExtensions.cs中,我以为我已经使该组件可用于PaController。 老实说,我不知道为什么它会在退货时抛出一个错误,所以任何build议/讨论/帮助都会受到欢迎。 我已经包含了3个文件的代码,我一直在搞,但如果你觉得我忘了发布一个需要诊断这个错误让我知道,我会发布它。 谢谢你的帮助!

PaController

 using System; using System.Collections.Generic; using System.Linq; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Web.UI.WebControls; using System.Web; using System.Web.Mvc; using DBFirstMVC.Models; using System.Data; using PagedList; using PagedList.Mvc; using DBFirstMVC.Controllers; using System.IO; using DBFirstMVC; using DBFirstMVC.CustomActionResults; namespace DBFirstMVC.Controllers { public class PaController : Controller { private PaEntities db = new PaEntities(); // // GET: /Pa/ public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page) { ViewBag.CurrentSort = sortOrder; ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "PA desc" : ""; ViewBag.MPSortParm = sortOrder == "MP" ? "MP desc" : "MP asc"; ViewBag.IASortParm = sortOrder == "IA" ? "IA desc" : "IA asc"; if (Request.HttpMethod == "GET") { searchString = currentFilter; } else { page = 1; } ViewBag.CurrentFilter = searchString; var IAMP = from p in db.iamp_mapping select p; if (!String.IsNullOrEmpty(searchString)) { IAMP = IAMP.Where(p => p.PA.ToUpper().Contains(searchString.ToUpper())); } switch (sortOrder) { case "Pa desc": IAMP = IAMP.OrderByDescending(p => p.PA); break; case "MP desc": IAMP = IAMP.OrderByDescending(p =>p.MAJOR_PROGRAM); break; case "MP asc": IAMP = IAMP.OrderBy(p =>p.MAJOR_PROGRAM); break; case "IA desc": IAMP = IAMP.OrderByDescending(p => p.INVESTMENT_AREA); break; case "IA asc": IAMP = IAMP.OrderBy(p => p.INVESTMENT_AREA); break; default: IAMP = IAMP.OrderBy(p => p.PA); break; } int pageSize = 25; int pageNumber = (page ?? 1); return View(IAMP.ToPagedList(pageNumber, pageSize)); } // // GET: /Pa/Details/5 public ActionResult Details(int id) { return View(); } // // GET: /Pa/Create public ActionResult Create() { return View(); } // // POST: /Pa/Create [HttpPost] public ActionResult Create(iamp_mapping IAMP) { try { using (var db = new PaEntities()) { db.iamp_mapping.Add(IAMP); db.SaveChanges(); } return RedirectToAction("Index"); } catch { return View(); } } // // GET: /Pa/Edit/5 public ActionResult Edit(string id) { using (var db = new PaEntities()) { return View(db.iamp_mapping.Find(id)); } } // // POST: /Pa/Edit/5 [HttpPost] public ActionResult Edit(string id, iamp_mapping IAMP) { try { using (var db = new PaEntities()) { db.Entry(IAMP).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction(""); } } catch { return View(); } } // // GET: /Pa/Delete/5 public ActionResult Delete(string id) { using (var db = new PaEntities()) { return View(db.iamp_mapping.Find(id)); } } // // POST: /Pa/Delete/5 [HttpPost] public ActionResult Delete(string id, iamp_mapping IAMP) { try { using (var db = new PaEntities()) { var vIAMP = db.iamp_mapping.Find(id); db.Entry(vIAMP).State = EntityState.Deleted; db.SaveChanges(); return RedirectToAction("Index"); } } catch (Exception e) { throw (e); //return View(); } } public ActionResult GenerateExcel1() { using (var db = new PaEntities()) { return this.Excel(db, db.iamp_mapping, "data.xls"); } } } } 

ExcelResult.cs

 using System; using System.Web.Mvc; using System.Data.Linq; using System.Collections; using System.IO; using System.Web.UI.WebControls; using System.Linq; using System.Web; using System.Web.UI; using System.Drawing; namespace DBFirstMVC { public class ExcelResult : ActionResult { private DataContext _dataContext; private string _fileName; private IQueryable _rows; private string[] _headers = null; private TableStyle _tableStyle; private TableItemStyle _headerStyle; private TableItemStyle _itemStyle; public string FileName { get { return _fileName; } } public IQueryable Rows { get { return _rows; } } public ExcelResult(DataContext dataContext, IQueryable rows, string fileName) : this(dataContext, rows, fileName, null, null, null, null) { } public ExcelResult(DataContext dataContext, string fileName, IQueryable rows, string[] headers) : this(dataContext, rows, fileName, headers, null, null, null) { } public ExcelResult(DataContext dataContext, IQueryable rows, string fileName, string[] headers, TableStyle tableStyle, TableItemStyle headerStyle, TableItemStyle itemStyle) { _dataContext = dataContext; _rows = rows; _fileName = fileName; _headers = headers; _tableStyle = tableStyle; _headerStyle = headerStyle; _itemStyle = itemStyle; // provide defaults if (_tableStyle == null) { _tableStyle = new TableStyle(); _tableStyle.BorderStyle = BorderStyle.Solid; _tableStyle.BorderColor = Color.Black; _tableStyle.BorderWidth = Unit.Parse("2px"); } if (_headerStyle == null) { _headerStyle = new TableItemStyle(); _headerStyle.BackColor = Color.LightGray; } } public override void ExecuteResult(ControllerContext context) { // Create HtmlTextWriter StringWriter sw = new StringWriter(); HtmlTextWriter tw = new HtmlTextWriter(sw); // Build HTML Table from Items if (_tableStyle != null) _tableStyle.AddAttributesToRender(tw); tw.RenderBeginTag(HtmlTextWriterTag.Table); // Generate headers from table if (_headers == null) { _headers = _dataContext.Mapping.GetMetaType(_rows.ElementType).PersistentDataMembers.Select(m => m.Name).ToArray(); } // Create Header Row tw.RenderBeginTag(HtmlTextWriterTag.Thead); foreach (String header in _headers) { if (_headerStyle != null) _headerStyle.AddAttributesToRender(tw); tw.RenderBeginTag(HtmlTextWriterTag.Th); tw.Write(header); tw.RenderEndTag(); } tw.RenderEndTag(); // Create Data Rows tw.RenderBeginTag(HtmlTextWriterTag.Tbody); foreach (Object row in _rows) { tw.RenderBeginTag(HtmlTextWriterTag.Tr); foreach (string header in _headers) { string strValue = row.GetType().GetProperty(header).GetValue(row, null).ToString(); strValue = ReplaceSpecialCharacters(strValue); if (_itemStyle != null) _itemStyle.AddAttributesToRender(tw); tw.RenderBeginTag(HtmlTextWriterTag.Td); tw.Write(HttpUtility.HtmlEncode(strValue)); tw.RenderEndTag(); } tw.RenderEndTag(); } tw.RenderEndTag(); // tbody tw.RenderEndTag(); // table WriteFile(_fileName, "application/ms-excel", sw.ToString()); } private static string ReplaceSpecialCharacters(string value) { value = value.Replace("'", "'"); value = value.Replace("“", "\""); value = value.Replace("”", "\""); value = value.Replace("–", "-"); value = value.Replace("…", "..."); return value; } private static void WriteFile(string fileName, string contentType, string content) { HttpContext context = HttpContext.Current; context.Response.Clear(); context.Response.AddHeader("content-disposition", "attachment;filename=" + fileName); context.Response.Charset = ""; context.Response.Cache.SetCacheability(HttpCacheability.NoCache); context.Response.ContentType = contentType; context.Response.Write(content); context.Response.End(); } } } 

ExcelControllerExtensions

 using System; using System.Web.Mvc; using System.Data.Linq; using System.Collections; using System.Web.UI.WebControls; using System.Linq; namespace DBFirstMVC.CustomActionResults { public static class ExcelControllerExtensions { public static ActionResult Excel ( this Controller controller, DataContext dataContext, IQueryable rows, string fileName ) { return new ExcelResult(dataContext, rows, fileName, null, null, null, null); } public static ActionResult Excel ( this Controller controller, DataContext dataContext, IQueryable rows, string fileName, string[] headers ) { return new ExcelResult(dataContext, rows, fileName, headers, null, null, null); } public static ActionResult Excel ( this Controller controller, DataContext dataContext, IQueryable rows, string fileName, string[] headers, TableStyle tableStyle, TableItemStyle headerStyle, TableItemStyle itemStyle ) { return new ExcelResult(dataContext, rows, fileName, headers, tableStyle, headerStyle, itemStyle); } } } 

Model1.context.cs

 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; namespace DBFirstMVC.Models { public partial class PaEntities : DbContext { public PaEntities() : base("name=PaEntities") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { throw new UnintentionalCodeFirstException(); } public DbSet<iamp_mapping> iamp_mapping { get; set; } public DbSet<pa_mapping> pa_mapping { get; set; } } } 

iamp_mapping.cs

 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; namespace DBFirstMVC.Models { public partial class iamp_mapping { public string PA { get; set; } public string MAJOR_PROGRAM { get; set; } public string INVESTMENT_AREA { get; set; } } } 

错误的原因是在消息中: cannot convert from 'DBFirstMVC.Models.PaEntities' to 'System.Data.Linq.DataContext 。 这意味着您的PaEntitiestypes不能转换为System.Data.Linq.DataContext ,因此您的Excel扩展方法的签名都不匹配您传递的参数。

什么是您的PaEntitiestypes? 它是否inheritance自System.Data.Linq.DataContext