Excel导出在Firefox中工作但不在IE中工作

时间:2011-02-28 19:24:19

标签: .net asp.net-mvc-2 firefox internet-explorer-8 export-to-excel

我的MVC应用程序中有Excel导出功能。这样做的方式是,我用这一行:

window.open((actionUrl + "?id=" + guid + "&viewName=" + viewUrl + "&fileName="  + fileName), null, null, null);

这使我能够通过URL将所有参数传递给MVC操作。行动如下:

public ActionResult ExportToExcel(Guid? id, string viewName, string fileName)
        {
            IndicationBase indication = CachedTransactionManager<IndicationBase>.GetCachedTransactions(id.Value);
            return new ExcelResult<Chatham.Web.Models.Indications.ModelBase>
            (
                ControllerContext,
                viewName,
                fileName,
                indication.Model
            );
        }

然后调用Excel结果,如下所示:

public class ExcelResult<Model> : ActionResult
    {
        string _fileName;
        string _viewPath;
        Model _model;
        ControllerContext _context;

        public ExcelResult(ControllerContext context, string viewPath, string fileName, Model model)
        {
            this._context = context;
            this._fileName = fileName;
            this._viewPath = viewPath;
            this._model = model;
        }
         protected string RenderViewToString()
        {
            using (var writer = new StringWriter())
            {
                var view = new WebFormView(_viewPath);
                var vdd = new ViewDataDictionary<Model>(_model);
                var viewCxt = new ViewContext(_context, view, vdd, new TempDataDictionary(), writer);
                viewCxt.View.Render(viewCxt, writer);
                return writer.ToString();
            }
        }
        void WriteFile(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 = "application/ms-excel";
            context.Response.Write(content);
            context.Response.End();
        }

        public override void ExecuteResult(ControllerContext context)
        {
            string content = this.RenderViewToString();
            this.WriteFile(content);
        }
    }

所有这些都适用于Firefox,但不适用于IE。可能是Response标题的内容吗?这是我的第一次猜测,但我甚至不知道从哪里开始寻找错误的东西。

从IE返回的错误是这样的: enter image description here

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:2)

不要设置

context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
IE中的