473,418 Members | 2,033 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,418 software developers and data experts.

How to return an excel file or excel data from ASP.NET

Here are some of the approaches.

1. Transform DataGrid

http://www.dotnetjohn.com/articles.aspx?articleid=36

3. Use the Export approach

http://www.aspnetpro.com/NewsletterA...200309so_l.asp

---->
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:

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

<%@ Page Language="vb" AutoEventWireup="false"
Codebehind="DataToExcel.aspx.vb" Inherits="DataToExcel" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>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

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.AppS ettings("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 Sub

End Class

This is really a simple solution to a common problem. Hope it works out
for you!

Jan 29 '06 #1
1 6102
Response.Clear();
Response.Buffer= true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition",
"inline;filename=Clientes.xls");
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new
System.Web.UI.HtmlTextWriter(oStringWriter);
DataGrid1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();

Jan 31 '06 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: RK | last post by:
Hi, In my application, I need to copy data from an Excel file into a SQL table. The article related to this can be found at http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B306572 ...
2
by: Niyazi | last post by:
Hi, I have to retrieve a data from AS400 DB2 and after working with data I have to export into one of existing Excel file. I can connect into specific library in AS400 DB2 using AS400...
3
by: Otie | last post by:
I found the following under the GetObject help notes and in the example for GetObject: "This example uses the GetObject function to get a reference to a specific Microsoft Excel worksheet...
2
by: jeffgeorge | last post by:
I'm currently exporting a form to Excel. Because there are controls and totals in the header, I first have a button for users to convert to a datasheet. Then I use the automated quick office...
2
by: Mad Scientist Jr | last post by:
>From an asp.net web page I want the user to open the results of a SQL query in Excel, as automatically as possible (ie not having to loop through columns, rows, in code). For this,...
4
by: somanyusernamesaretakenal | last post by:
What I am trying to achieve: Basically I have generated a report in access. This report needs to be updated using excel. (Updating the new data, not changing existing data) What I did was I...
2
by: =?Utf-8?B?TEJU?= | last post by:
Good Day, I have a web application created using ASP.NET (with VB.NET). The application allow user to browse Excel raw data file then the program will grab data from the file to perform further...
7
by: TG | last post by:
hi! I am trying to create a sql server table from an excel sheet. Here is the code I have: 'This procedure the xlsx file and dumps it to a table in SQL Server
3
by: =?Utf-8?B?YzY3NjIyOA==?= | last post by:
Hi all, I have a question for you. I have a .csv file which has many lines of data. Each line has many data fields which are delimited by ",". Now I need to extract part of data from this...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.