Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export GridView to Excel without losing grid lines in Excel

I have a GridView that I want to export to Excel. When I use the sample code I find online, it exports the content to Excel just fine, but for some reason it also clears out all grid lines outside of my exported table.

For your average excel user this is easy enough to fix, but I need this solution to work for everyone.

So then is there a way to export the data in a GridView into an Excel Workbook so that it looks like it was just typed into Excel? I've pasted the code I am using below, assume that a GridView called 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: Found one partial solution. If I export as a comma-delimited list and set the header to be a CSV file, it opens fine and all grid lines (even those outside of the exported data) are showing. The only problem with this of course is having to strip out every comma and newline character from my values before exporting them.

like image 604
Justin C Avatar asked Dec 22 '22 05:12

Justin C


1 Answers

The following Post gave me the answer. http://forums.asp.net/t/1074110.aspx I will summarize what to do with the code.

System.IO.StringWriter dvWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter OutputGenerator = new System.Web.UI.HtmlTextWriter(dvWriter);

            //To put in the excel gridlines 
            dvWriter.Write(@"<html xmlns:x=""urn:schemas-microsoft-com:office:excel"">");
            dvWriter.Write(@"<head>
                               <xml>
                                 <x:ExcelWorkbook> 
                                    <x:ExcelWorksheets>
                                       <x:ExcelWorksheet>
                                          <x:WorksheetOptions>
                                             <x:Panes></x:Panes>
                                             <x:Print><x:Gridlines /></x:Print>
                                          </x:WorksheetOptions>
                                        </x:ExcelWorksheet>
                                      </x:ExcelWorksheets>
                                    </x:ExcelWorkbook>
                                  </xml>
                                </head>");
//*******Put your Table Body here *******
like image 62
Mistlin Avatar answered Dec 28 '22 07:12

Mistlin