I am having trouble exporting data to Excel. The following seems to render the gridview into my View, instead of prompting the user to open with Excel, which I have installed on my machine.
Public ActionResult ExportToExcel() { var products = this.Repository.Products.ToList(); var grid = new GridView(); grid.DataSource = from p in products select new { Id = p.Id, Name = p.Name }; grid.DataBind(); Response.ClearContent(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls"); Response.ContentType = "application/ms-excel"; Response.Charset = ""; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); grid.RenderControl(htw); Response.Output.Write(sw.ToString()); Response.Flush(); Response.End(); return View("MyView"); }
What am I doing wrong?
Add a link button in the View and name it DownloadExcel. Now, create a Method in Controller and add the following code to Export the data in Excel. Now, run the project and click on the "Download Excel" button. The data is downloaded in Excel format.
Steps to create Excel file in ASP.NET MVC, programmatically: Step 1: Create a new ASP.NET web application project. Step 2: Complete the New ASP.NET Web Application – CreateXlsIOSample dialog: Select MVC.
I have tried your code and it works just fine. The file is being created without any problem, this is the code I used (it's your code, I just changed the datasource for testing):
public ActionResult ExportToExcel() { var products = new System.Data.DataTable("teste"); products.Columns.Add("col1", typeof(int)); products.Columns.Add("col2", typeof(string)); products.Rows.Add(1, "product 1"); products.Rows.Add(2, "product 2"); products.Rows.Add(3, "product 3"); products.Rows.Add(4, "product 4"); products.Rows.Add(5, "product 5"); products.Rows.Add(6, "product 6"); products.Rows.Add(7, "product 7"); var grid = new GridView(); grid.DataSource = products; grid.DataBind(); Response.ClearContent(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls"); Response.ContentType = "application/ms-excel"; Response.Charset = ""; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); grid.RenderControl(htw); Response.Output.Write(sw.ToString()); Response.Flush(); Response.End(); return View("MyView"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With