I have a GridView that I want to export to Excel. When I use the sample code that I found on the Internet, it exports the contents to Excel just fine, but for some reason, it also clears all the grid lines outside the exported table.
For your regular excel user, this is easy enough to fix, but I need this solution to work for everyone.
So, is there a way to export data in a GridView to an Excel workbook so that it looks like it was entered into Excel? I pasted the code that I use below, suppose a GridView with the name toPrint exists and has accurate data.
Response.Clear(); Response.AddHeader("content-disposition", "attachment; filename=" + name + "_Registration_Forms.xls"); Response.Charset = ""; Response.ContentType = "application/vnd.ms-excel"; Page.EnableViewState = false; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); toPrint.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End();
EDIT: one partial solution found. If I export as a comma-delimited list and set the title to a CSV file, it opens normally and all grid lines (even those that are outside the exported data) are displayed. The only problem with this, of course, is to cut out every comma and newline from my values ββbefore exporting them.
source share