Click here to Skip to main content
14,883,063 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I want to save my view result in web to excel and or PDF. I must show dialog save to make path and choose the file's extension to make file. I use asp.net, Could you help me how to do this?

What I have tried:

public ActionResult Export2Excel()
  {
      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");


      var grid = new GridView();
      grid.DataSource = products;
      grid.DataBind();

      Response.ClearContent();
      Response.Buffer = true;
      Response.AddHeader("content-disposition", "attachment; filename=Result.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");
  }
Posted
Updated 4-Sep-17 18:30pm

1 solution

Here is a link that will show you how to export in both C# and VB: How to Export GridView To Word/Excel/PDF/CSV in ASP.Net | The ASP.NET Forums[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900