[英]Export the Table View in an Excel sheet in asp.net mvc
我想導出Razor視圖表的Excel工作表。 此代碼顯示該表:
public ActionResult Show(int id)
{
IEnumerable<GradeSheetViewModel> model = _repGrade.GetList(id);
return View(model);
}
這是導出到Excel函數的代碼
public ActionResult ExportToExcel()
{
var gv = new GridView();
gv.DataSource = this.Show();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=DemoExcel.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter objStringWriter = new StringWriter();
HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter);
gv.RenderControl(objHtmlTextWriter);
Response.Output.Write(objStringWriter.ToString());
Response.Flush();
Response.End();
return View("Index");
}
但是它給出了錯誤
gv.DataSource = this.Show();
錯誤是
方法Show的重載沒有接受0參數
DataSource
屬性分配需要IEnumerable
作為其源。 您需要更改Show
方法以返回實現IEnumerable
所有對象(例如List
),並使用id
參數調用它,如下所示:
// Get list object
public List<GradeSheetViewModel> Show(int id)
{
return _repGrade.GetList(id);
}
// Controller
public ActionResult ExportToExcel(int id)
{
var gv = new GridView();
gv.DataSource = Show(id);
// other stuff
}
補充說明1:如果要用戶下載文件,則應將文件作為FileResult
返回,而不是添加Response
和返回視圖:
public ActionResult ExportToExcel(int id)
{
var gv = new GridView();
gv.DataSource = Show(id);
gv.DataBind();
// save the file and create byte array from stream here
byte[] byteArrayOfFile = stream.ToArray();
return File(byteArrayOfFile, "application/vnd.ms-excel", "DemoExcel.xls");
}
附加說明2:避免在MVC控制器中使用諸如GridView
類的Webforms服務器控件。 您可以從本期中選擇一種可用的替代方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.