Export DataSets to Excel ...

xiaoxiao2021-03-06  67

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 communications SO That We can pass in diffrent Kinds of Information:

OVERLOAD # 1

A dataset the response object of the web page overload # 2

A Dataset An Index Value of Which Table from The DataSet The Response Object of The Web Page Overload # 3

A DataSet The Table Name of a Table in The DataSet The Response Object of The Web Page

The method of 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 usePublic 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 () 'TE ll 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 clef an 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.Database ()'

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 SubEnd ClassEditor's Note: The class above was compiled using the following Visual Basic Compiler Directive:

VBRARY /R: SyiStem.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 does not 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.

Here's The Code for the Calling page. First The .aspx Page Which Is Really Just A Shell To Give US Sometting To Call. As Usual, All The Work Is Done in the code-behind file.

DataToExcel.aspx

<% @ Page language = "vb" autoeventwireup = "false" codebehind = "datatoExcel.aspx.vb" inherits = "DatatoExcel"%> DatasettoExcel </ title> <meta name = "generator" content = "Microsoft Visual Studio .NET 7.1> <meta name =" code_language "content =" Visual Basic .NET 7.1 "> <meta name = "vs_defaultClientScript" content = "JavaScript"> <meta name = "vs_targetSchema" content = "http://schemas.microsoft.com/intellisense/ie5"> </ head> <body MS_POSITIONING = "GridLayout"> <form id = "form1" method = "post" runat = "server"> </ form> </ body> </ html> datatoExcel.aspx.vb</p> <p>Public Class DataToExcel Inherits System.Web.UI.Page # Region "Web Form Designer Generated Code" 'This call is required by the Web Form Designer <System.Diagnostics.DebuggerStepThrough ()> Private Sub InitializeComponent () End Sub.' NOTE: The following placeholder declaration is required by the Web Form Designer. 'Do not delete or move it. Private designerPlaceholderDeclaration As System.Object Private Sub Page_Init (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init' CODEGEN : This method call is required by the Web Form Designer 'Do not modify it using the code editor InitializeComponent () End Sub # End Region Private Sub Page_Load (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.. Load Dim myConnection As New SqlClient.SqlConnection (ConfigurationSettings.AppSettings ( "PubsConnection")) Dim cmd As New SqlClient.SqlCommand ( "select * from authors", myConnection) Dim da As New SqlClient.SqlDataAdapter (cmd) 'Instantiate a dataset Dim ds As New DataSet Try' populate the dataset da.Fill (ds) Finally 'check on connection status If myConnection.State = ConnectionState.Open Then myConnection.Close () End If' get rid of connection object myConnection. Dispose () End Try 'Call Our Class Method DatasettoExcel.convert (DS, Response) End Subend ClassThis Is Really A Simple Solution To A Common Problem. Hope IT Works Out for you!</p> <p>You May Run The Program Here.you May Download The Code Here.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-110076.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="110076" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.046</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'TnqmvADnAFRCexRetEeLSOk0rvz8XjyTmTjXH1lXEgb2D3Mv_2BOx0drpprHkNmzGcVrMNS6TAi1xXpRWB'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>