Friday, September 22, 2006

Exporting a Data Grid to Excel

This article will teach you about exporting a data to excel.

In most of the application we need to export the data to excel. We need to do a lot of formatting to the data (tabular form, seeting the widht, height of the cell etc). Formattign the data using excel automation is a tedious job.

 The method which i am going to tell you now is going to be very simple. Excel can also be compared with HTML table, Excel work sheet is a matrix of rows and columns.

Generating an excel from aspx is very simple we need to format the html table with data and the change the contect type alone and print the table on the page using response.write. For changing the content type use the following code.

[code]
  Response.ClearContent()
  Response.ClearHeaders()
  Response.ContentType = “application/vnd.ms-excel”
[/code]

 Again most of us fail to format the data propoerly in a HTML table. But we all know how to work with the datagrid and also that the final rendered out put of the datagrid is HTML tags that is a table.

 So all we need is bind the dataset to the datagrid, format the datagird, then get the HTML output (render the html output) and print it. Use the following code for that.

 [code]
   Dim dg As New DataGrid
   Dim sw As New System.IO.StringWriter
   Dim htw As New System.Web.UI.HtmlTextWriter(sw)
   dg.RenderControl(htw)
   Response.Write(sw.ToString)
   Response.End()
[/code]

Is it not simple

Posted by Sadha at 11:50:33
Comments

One Response to “Exporting a Data Grid to Excel”

  1. hey,where are you from??can u email me please,thx

Leave a Reply