1

我已经在互联网上搜索了好几天了,我只是想知道是否有人使用 MVC 3 将数据导出到 excel。我真的需要一个很好的教程,其中包含有关如何使用导出 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)' 有一些无效参数 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。老实说,我不知道为什么它会在返回时抛出错误,因此欢迎任何建议/讨论/帮助。我已经包含了我一直在弄乱的 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");
            }
        }









    }
}

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);
        }

    }
}

模型1.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; }
    }

}
4

1 回答 1

2

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

你是什​​么PaEntities类型的?它继承自System.Data.Linq.DataContext?

于 2012-04-03T22:08:06.193 回答