简体   繁体   中英

Export the Table View in an Excel sheet in asp.net mvc

I want to export the Excel sheet of my Razor view table. This code shows the table:

public ActionResult Show(int id)
    {
        IEnumerable<GradeSheetViewModel> model = _repGrade.GetList(id);
        return View(model);
    }

Here is the code for export to Excel function

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

but it gives the error at

gv.DataSource = this.Show();

the error is

no overload for the method Show takes 0 argument

DataSource property assignment requires IEnumerable as its source. You need to change Show method to return any objects that implements IEnumerable (eg List ) and call it with id parameter like this:

// 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
}

Additional note 1: If you want user to download the file you should return file as FileResult instead of adding Response and returning view:

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

Additional note 2: Avoid using webforms server controls like GridView in MVC controller. You can choose one of available alternatives from this issue .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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