2011-02-23 68 views
0
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調用中獲取數據。定製Excel導出操作

任何幫助都會很棒。謝謝。

+0

您無法從AJAX調用下載文件。 – ZippyV 2011-02-24 08:57:34

回答

0

與所有行動的結果,你會從行動回報他們:

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

在這個例子中Foo部分是強類型的視圖模型和包含的數據。

+0

Ahhh好吧我不知道如何通過ControllerContext(我想這是一個擴展),我每天都在學習越來越多!另外,我不確定是否應該使用Excel Return類型或Action Result類型聲明它。 – slandau 2011-02-24 14:06:51