Custom Excel Export Action

 ̄綄美尐妖づ 提交于 2019-12-11 22:53:45

问题


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

I'm really just confused on how to use this action in my controller. I got this from the internet but I am just having a hard time figuring out how I would define it in my controller and pass data to it and get data back from an AJAX call.

Any help would be awesome. Thanks.


回答1:


As with all action results you would return them from an action:

public ActionResult Foo()
{
    SomeViewModel model = ...
    return new ExcelResult<SomeViewModel>
    (
        ControllerContext,
        "~/Views/Home/Foo.ascx",
        "Foo.xlsx",
        model
    );
}

In this example the Foo partial is strongly typed to a view model and contains the data.



来源:https://stackoverflow.com/questions/5096370/custom-excel-export-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!