0

I have some default functionality in a C# asp.net web application that will export a gridview to an excel file. This code is working great in Excel 2007, however it will not open in 2010. I need to upgrade this code to work in both, or find a new solution. Any help would be great.

Current code:

            gvReport.Style.Add("font-size", "1em");
            Response.Clear();
            string attachment = "attachment; filename=FileName.xls";
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gvReport.GridLines = GridLines.Horizontal;
            gvReport.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
EvanGWatkins
  • 1,427
  • 6
  • 23
  • 52
  • 1
    What error do you get trying to open in Excel 2007+? My guess is you are running into a security issue and not an excel problem. – Robert Beaubien May 07 '12 at 18:38
  • You're not exporting it as OpenXML btw. You're exporting it as HTML that excel (obviously not 2010) can understand. Your best bet is EPP like Antonio suggested. – banging May 07 '12 at 19:03

1 Answers1

2

Use EPPlus and export data to Excel, I presume that gvReport iz GridView control, so use data that you bind to that GridView and export it with EPPlus.

It's pretty easy, here you can find example of ashx handler that will return excel file created from DataTable :

https://stackoverflow.com/a/9569827/351383

Community
  • 1
  • 1
Antonio Bakula
  • 20,445
  • 6
  • 75
  • 102