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

[ 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"">
                      br {mso-data-placement:same-cell;}
                      tr {vertical-align:top;}

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>";

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-2024  |  Page Processed at 2024-06-18 5:25:46 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search