繁体   English   中英

在asp.net mvc中的Excel工作表中导出表视图

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM