我一直在互联网上搜索几天,我只是想知道是否有人在使用MVC 3将数据导出到excel时做了任何工作。我真的需要一个很好的教程,有关如何导出的分步说明使用带C#的MVC 3来优化数据。我发现了很多文章,但它们似乎都不适用于我现有的数据库。我只是在寻找关于在何处放置方法等的一些说明。本教程http://stephenwalther.com/blog/archive/2008/06/16/asp-net-mvc-tip-2-create-a-custom-action-result-that-returns-microsoft-excel-documents.aspx 似乎强烈建议堆栈溢出。我已经按照文章的说明写了这封信,但我无法运行该程序,因为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)'has 一些无效的参数C:\ Documents and Settings \ lk230343 \ My Documents \ Visual Studio 2010 \ WebSites \ DBFirstMVC 保存\ DBFirstMVC_CRUD_and_PAGING_done \ DBFirstMVC \ Controllers \ PaController.cs 193 24 DBFirstMVC
错误2参数2:无法从'DBFirstMVC.Models.PaEntities'转换 到'System.Data.Linq.DataContext'C:\ Documents and 设置\ lk230343 \ My Documents \ Visual Studio 2010 \ WebSites \ DBFirstMVC 保存\ DBFirstMVC_CRUD_and_PAGING_done \ DBFirstMVC \ Controllers \ PaController.cs 193 35 DBFirstMVC
有没有人见过这些错误或对我如何修复它们有任何想法?我的意思是excel方法存在于ExcelControllerExtensions.cs中,我想我已经将该程序集用于PaController。老实说,我不知道为什么它会在返回时抛出错误,所以任何建议/讨论/帮助都会受到欢迎。我已经包含了我一直在搞乱的3个文件的代码,但如果你认为我忘了发布一个诊断此错误所需的信息让我知道,我会发布它。谢谢你的帮助!
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");
}
}
}
}
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();
}
}
}
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);
}
}
}
//------------------------------------------------------------------------------
// <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; }
}
}
//------------------------------------------------------------------------------
// <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; }
}
}
答案 0 :(得分:1)
错误原因就在消息中:cannot convert from 'DBFirstMVC.Models.PaEntities' to 'System.Data.Linq.DataContext
。这意味着您PaEntities
类型无法转换为System.Data.Linq.DataContext
,因此您的Excel
扩展方法'签名都不会与您传递的参数相匹配。
您的PaEntities
类型是什么?它是否继承自System.Data.Linq.DataContext
?