我要导出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个参数
答案 0 :(得分: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服务器控件。您可以从this issue中选择一种可用的替代方法。