首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在asp.net mvc中导出Excel表格中的表视图

在asp.net mvc中导出Excel表格中的表视图
EN

Stack Overflow用户
提问于 2018-08-08 05:16:57
回答 1查看 1.2K关注 0票数 0

我想导出我的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();

错误是

方法没有重载,参数为0

EN

回答 1

Stack Overflow用户

发布于 2018-08-08 11:45:21

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");
}

MVC附加说明2:避免在控制器中使用webforms服务器控件,如GridView。您可以从this issue中选择一个可用的替代方案。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51735559

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档