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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (77)

我想导出我的剃须刀视图表的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参数

提问于
用户回答回答于

你需要改变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
}

如果希望用户下载该文件,则应将文件返回为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");
}

扫码关注云+社区

领取腾讯云代金券