簡體   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