create csv file in asp.net

  • Thread starter Thread starter J
  • Start date Start date
J

J

hi, all,
I have an asp.net page which let user view data from database (using dataset),
but now, how can I create a CSV file in asp.net then let user save to their
local machine?
Thanks in advance.
J.
 
Hi J,

Here's some code that should get you going. It grabs data from the SQL
database as a datareader and pushes it out as a CSV. No storage of the file
required. You should see Excel open with the data.

Does this help?

Ken
Microsoft MVP [ASP.NET]


Imports System.Data.SqlClient
Imports System.IO
Public Class csv
Inherits System.Web.UI.Page
Protected WithEvents Button1 As _
System.Web.UI.WebControls.Button
Protected WithEvents SqlConnection1 As _
System.Data.SqlClient.SqlConnection
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.SqlConnection1 = _
New System.Data.SqlClient.SqlConnection
'
'SqlConnection1
'
Me.SqlConnection1.ConnectionString = _
"data source=P4320;initial catalog=" & _
"Northwind;password="""";persist security info=Tru" & _
"e;user id=sa;workstation id=P4320;packet size=4096"
End Sub
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 Button1_Click _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
'Set the appropriate ContentType.
Dim filename As String = "orderdetails.csv"
Dim myCommand As New SqlCommand _
("select * from [order details] ", SqlConnection1)
myCommand.Connection.Open()
Dim myReader As SqlDataReader = _
myCommand.ExecuteReader _
(CommandBehavior.CloseConnection)
Dim i As Integer
Dim sb As New System.Text.StringBuilder
For i = 0 To myReader.FieldCount - 1
If i < (myReader.FieldCount - 1) Then
sb.Append(Chr(34) & myReader.GetName(i) & _
Chr(34) & ",")
Else
sb.Append(Chr(34) & myReader.GetName(i) & _
Chr(34) & vbCrLf)
End If
Next
While myReader.Read()
For i = 0 To myReader.FieldCount - 1
If i < (myReader.FieldCount - 1) Then
sb.Append(Chr(34) & _
myReader.GetValue(i).ToString & Chr(34) & ",")
Else
sb.Append(Chr(34) & _
myReader.GetValue(i).ToString & Chr(34) & vbCrLf)
End If
Next
End While
myReader.Close()
SqlConnection1.Close()
Response.ContentType = "Application/x-msexcel"
Response.AddHeader _
("content-disposition", "attachment; filename=""" & _
filename & """")
'Write the file directly to the HTTP output stream.
Response.Write(sb.ToString)
Response.End()
End Sub
End Class



<%@ Page Language="vb" AutoEventWireup="false" Codebehind="csv.aspx.vb"
Inherits="p4320work.csv"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>csv</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="FlowLayout">
<form id="Form1" method="post" runat="server">
<asp:Button id="Button1" runat="server" Text="Launch"></asp:Button>
</form>
</body>
</HTML>
 
Hi, Ken, when I run your demo file, I got this error message:

Parser Error Message: Could not load type 'p4320work.csv'.
Source Error:
Line 1: <%@ Page Language="vb" AutoEventWireup="false"
Codebehind="WebForm1.aspx" Inherits="p4320work.csv"%>
Line 2: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
Line 3: <HTML>

Even I made a fake 'p4320work.csv' which is 0 byte, still not works. Did this
means I need a real 'p4320work.csv' in the project folder?

Thanks.
J.



Hi J,

Here's some code that should get you going. It grabs data from the SQL
database as a datareader and pushes it out as a CSV. No storage of the file
required. You should see Excel open with the data.

Does this help?

Ken
Microsoft MVP [ASP.NET]
 
That was sample code that won't run on a different system without changes.

The part you mention is a reference to the class in the codebehind.
p4320work is the name of my project and csv was the name of my class.

You need to change it to the name of the class in your own page. It will be
something like myprojectname.webform1 .

You'll also need to change the SQL Server config and password info too.



J said:
Hi, Ken, when I run your demo file, I got this error message:

Parser Error Message: Could not load type 'p4320work.csv'.
Source Error:
Line 1: <%@ Page Language="vb" AutoEventWireup="false"
Codebehind="WebForm1.aspx" Inherits="p4320work.csv"%>
Line 2: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
Line 3: <HTML>

Even I made a fake 'p4320work.csv' which is 0 byte, still not works. Did this
means I need a real 'p4320work.csv' in the project folder?

Thanks.
J.



Hi J,

Here's some code that should get you going. It grabs data from the SQL
database as a datareader and pushes it out as a CSV. No storage of the file
required. You should see Excel open with the data.

Does this help?

Ken
Microsoft MVP [ASP.NET]
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="csv.aspx.vb"
Inherits="p4320work.csv"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>csv</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="FlowLayout">
<form id="Form1" method="post" runat="server">
<asp:Button id="Button1" runat="server" Text="Launch"></asp:Button>
</form>
</body>
</HTML>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top