Export DataSets to Excel...

Often we need to load the data from a dataset into an excel spreadsheet to be manipulated and/or saved off to a local file. There are several ways to accomplish this using either Crystal Reports or ActiveReports. However there is a simple, elegant way to do the same thing without the need for a reporting tool.


By: Ken Walker Date: March 14, 2003 Download the code. Article Rating: 4.5 Printer Friendly Version


This article will show how to create a class which does the export. The class contains a convert method which has three overloads so that we can pass in different kinds of information:

  1. Overload #1 1. A Dataset 2. The response object of the web page
  2. Overload #2 1. A Dataset 2. An index value of which table from the dataset 3. The response object of the web page
  3. Overload #3 1. A Dataset 2. The table name of a table in the dataset 3. The response object of the web page

The methods will be shared methods so that we don’t have to instaniate the class in order to use the method.

What makes this task so straight forward is the elegance of the .NET Framework design. It turns out that most web controls have a RenderControl method which will write an html text stream. All we need to do is set up the response object, call the RenderControl method of a datagrid and tell the response object to output the "rendering". Pretty simple!

Here’s the code for the class (DataSetToExcel.vb):

'Class to convert a dataset to an html stream which can be used to display the dataset
'in MS Excel
'The Convert method is overloaded three times as follows
' 1) Default to first table in dataset
' 2) Pass an index to tell us which table in the dataset to use
' 3) Pass a table name to tell us which table in the dataset to use

Public Class DataSetToExcel

Public Shared Sub Convert(ByVal ds As DataSet, ByVal response As HttpResponse)
'first let's clean up the response.object
response.Clear()
response.Charset = ""
'set the response mime type for excel
response.ContentType = "application/vnd.ms-excel"
'create a string writer
Dim stringWrite As New System.IO.StringWriter
'create an htmltextwriter which uses the stringwriter
Dim htmlWrite As New System.Web.UI.HtmlTextWriter(stringWrite)
'instantiate a datagrid
Dim dg As New DataGrid
'set the datagrid datasource to the dataset passed in
dg.DataSource = ds.Tables(0)
'bind the datagrid
dg.DataBind()
'tell the datagrid to render itself to our htmltextwriter
dg.RenderControl(htmlWrite)
'all that's left is to output the html
response.Write(stringWrite.ToString)
response.End()
End Sub

Public Shared Sub Convert(ByVal ds As DataSet, ByVal TableIndex As Integer, ByVal response As HttpResponse)
'lets make sure a table actually exists at the passed in value
'if it is not call the base method
If TableIndex > ds.Tables.Count - 1 Then
Convert(ds, response)
End If
'we've got a good table so
'let's clean up the response.object
response.Clear()
response.Charset = ""
'set the response mime type for excel
response.ContentType = "application/vnd.ms-excel"
'create a string writer
Dim stringWrite As New System.IO.StringWriter
'create an htmltextwriter which uses the stringwriter
Dim htmlWrite As New System.Web.UI.HtmlTextWriter(stringWrite)
'instantiate a datagrid
Dim dg As New DataGrid
'set the datagrid datasource to the dataset passed in
dg.DataSource = ds.Tables(TableIndex)
'bind the datagrid
dg.DataBind()
'tell the datagrid to render itself to our htmltextwriter
dg.RenderControl(htmlWrite)
'all that's left is to output the html
response.Write(stringWrite.ToString)
response.End()
End Sub

Public Shared Sub Convert(ByVal ds As DataSet, ByVal TableName As String, ByVal response As HttpResponse)
'let's make sure the table name exists
'if it does not then call the default method
If ds.Tables(TableName) Is Nothing Then
Convert(ds, response)
End If
'we've got a good table so
'let's clean up the response.object
response.Clear()
response.Charset = ""
'set the response mime type for excel
response.ContentType = "application/vnd.ms-excel"
'create a string writer
Dim stringWrite As New System.IO.StringWriter
'create an htmltextwriter which uses the stringwriter
Dim htmlWrite As New System.Web.UI.HtmlTextWriter(stringWrite)
'instantiate a datagrid
Dim dg As New DataGrid
'set the datagrid datasource to the dataset passed in
dg.DataSource = ds.Tables(TableName)
'bind the datagrid
dg.DataBind()
'tell the datagrid to render itself to our htmltextwriter
dg.RenderControl(htmlWrite)
'all that's left is to output the html
response.Write(stringWrite.ToString)
response.End()
End Sub

End Class

Editor's Note: The class above was compiled using the following Visual Basic Compiler directive:

vbc /t:library /r:system.dll /r:system.web.dll /r:system.data.dll /r:system.xml.dll DataSetToExcel.vb

My example web page is based upon creating a dataset from SQL Server (the authors table from the pubs database), but it doesn’t matter how you get the dataset created, so modify your page according to your methodology. The example simply creates the dataset and calls the class method from the Page_Load event handler of the page.

Here’s the code for the calling page. First the .aspx page which is really just a shell to give us something to call. As usual, all the work is done in the code-behind file.

DataToExcel.aspx

1@ Page Language="vb" AutoEventWireup="false" Codebehind="DataToExcel.aspx.vb" Inherits="DataToExcel" 
 1<html>
 2<head>
 3<title>DataSetToExcel</title>
 4<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"/>
 5<meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE"/>
 6<meta content="JavaScript" name="vs_defaultClientScript"/>
 7<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema"/>
 8</head>
 9<body ms_positioning="GridLayout">
10<form id="Form1" method="post" runat="server">
11</form>
12</body>
13</html>

DataToExcel.aspx.vb

Public Class DataToExcel
Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.

 1<system.diagnostics.debuggerstepthrough()> Private Sub InitializeComponent()   
 2  
 3End Sub   
 4  
 5'NOTE: The following placeholder declaration is required by the Web Form Designer.    
 6'Do not delete or move it.    
 7Private designerPlaceholderDeclaration As System.Object   
 8  
 9Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init   
10'CODEGEN: This method call is required by the Web Form Designer    
11'Do not modify it using the code editor.    
12InitializeComponent()   
13End Sub   
14  
15#End Region   
16  
17Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load   
18Dim myConnection As New SqlClient.SqlConnection(ConfigurationSettings.AppSettings("PubsConnection"))   
19Dim cmd As New SqlClient.SqlCommand("select * from authors", myConnection)   
20Dim da As New SqlClient.SqlDataAdapter(cmd)   
21'instantiate a dataset    
22Dim ds As New DataSet   
23Try   
24'populate the dataset    
25da.Fill(ds)   
26Finally   
27'check on connection status    
28If myConnection.State = ConnectionState.Open Then   
29myConnection.Close()   
30End If   
31'get rid of connection object    
32myConnection.Dispose()   
33End Try   
34'call our class method    
35DataSetToExcel.Convert(ds, Response)   
36End Sub   
37  
38End Class   
39---  
40  
41This is really a simple solution to a common problem. Hope it works out for you! 
42
43You may run the program here.   
44You may download the code here.</system.diagnostics.debuggerstepthrough()>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus