2014-02-10 97 views
0

我試圖導出數據到excel表。導出到MVC中的Excel

我嘗試下面的代碼:

var grid = new System.Web.UI.WebControls.GridView(); 
var dbcontext = new HotelDbContext(); 
grid.DataSource = dbcontext.Database.SqlQuery<ReportsDTO>("Usp_GetDaysBillReport").ToList(); 
grid.DataBind(); 
Response.ClearContent(); 
Response.Buffer = true; 
Response.AddHeader("content-disposition", "attachment; filename=Marklist.xls"); 
Response.ContentType = "application/ms-excel"; 
Response.Charset = ""; 
StringWriter sw = new StringWriter(); 
HtmlTextWriter htw = new HtmlTextWriter(sw); 
grid.RenderControl(htw); 
Response.Output.Write(sw.ToString()); 
Response.Flush(); 
Response.End(); 

我沒有得到任何錯誤,也沒有文件的下載。

+0

你在哪裏有這樣的代碼(控制器,視圖等)? – wdosanjos

+0

我在控制器中有這些代碼。 – user3172321

回答

0

請嘗試在你的控制器的情況如下:

public FileContentResult DownloadExcel() 
    { 
     var grid = new System.Web.UI.WebControls.GridView(); 
     var dbcontext = new HotelDbContext(); 
     grid.DataSource = dbcontext.Database.SqlQuery<ReportsDTO>("Usp_GetDaysBillReport").ToList(); 
     grid.DataBind(); 
     StringWriter sw = new StringWriter(); 
     HtmlTextWriter htw = new HtmlTextWriter(sw); 
     grid.RenderControl(htw); 

     return File(Encoding.UTF8.GetBytes(sw.ToString()), 
        "application/ms-excel", 
        "Marklist.xls"); 
    }