自定义Excel导出操作

自定义Excel导出操作

本文介绍了自定义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);
        }
    }

我真的只是如何在我的控制器使用此动作困惑。我得到这个从互联网上,但我只是有一个很难搞清楚我怎么会在我的控制器定义它并传递数据给它,并从AJAX调用找回数据。

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.

推荐答案

与所有行动的结果,你会从行动回报他们:

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.

这篇关于自定义Excel导出操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 04:01