CodeSnip:Export DataTable to Excel
page 1 of 1
Published: 29 Nov 2004
Unedited - Community Contributed
Abstract
There are many examples of exporting DataSets to Excel, but this example handles newlines within a cell and renders it correctly.
by Michelle Beall
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 39748/ 44

[ Download Code ]

There is a quick trick to ensuring newlines are handled correctly when rendering a DataTable to Excel.  The key is adding the following style:

tr { mso-data-placement: same-cell; }

The example demonstrates assigning a DataTable to a DataGrid's DataSource and then using an HtmlTextWriter to render the DataGrid control.  The result is then written via the Response object.  In order to handle newlines the style needs to be streamed out to the Response object before the data.

This is accomplished by the following:

string header = @"<html xmlns:x=""urn:schemas-microsoft-com:office:excel"">
                    <head>
                      <style>
                      <!--table
                      br {mso-data-placement:same-cell;}
                      tr {vertical-align:top;}
                      -->
                      </style>
                    </head>
                    <body>";
Response.Write(header);

The header is included because the ExcelUtil.cs class clears the Response object before rendering any data.  After the data is written to the Response object the stream is concluded by writing out the body and HTML end tags.

string footer = "</body></HTML>";
Response.Write(footer);

Download the example to see the code in action.



User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2017 ASPAlliance.com  |  Page Processed at 2017-03-24 1:59:48 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search