Request and output CSV file from asp.net

M

Matt Auld

I need to produce on demand a csv output file from a asp.net client.
The backend db is SQL Server 7.0.

Can anyone please recommend a solution?

cheers
Matt
 
J

Jack Li

Hi Matt,

You can connect to the database, retrieve the data and construct a
stringbuilder formatted based on csv format, and then right it to the
client. I have a simlar example which retrieve data and display it in Excel
format. Please see if it is useful to you?

private void Page_Load(object sender, System.EventArgs e)
{
Response.ContentType = "application/ms-excel";
Response.AddHeader("Content-Disposition", "inline;filename=rawdata.xls");
Response.Buffer = true;
this.EnableViewState = false;

SqlConnection conn = new
SqlConnection(ConfigurationSettings.AppSettings["conn"]); // replace with
your connection string
conn.Open();
string sql = "SELECT * FROM rawdata ORDER BY createdate"; // replace
with your sql statement
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds);

StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.AllowPaging = false;
dg.DataBind();
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
conn.Close();
}

Regards,
Jack Li
MVP (ASP.NET)
 
P

Paul Clement

¤ I need to produce on demand a csv output file from a asp.net client.
¤ The backend db is SQL Server 7.0.
¤
¤ Can anyone please recommend a solution?

A number of ways to do this. The following uses SQL to export directly from SQL Server:

Function ExportSQLServerToText() As Boolean

Dim TextConnection As New
System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & "E:\My
Documents\TextFiles" & ";" & _
"Extended
Properties=""Text;HDR=NO;""")

TextConnection.Open()

Dim TextCommand As New System.Data.OleDb.OleDbCommand("SELECT * INTO [Orders#csv] FROM
[Orders] IN '' [ODBC;Driver={SQL
Server};Server=(local);Database=Northwind;Trusted_Connection=yes];", TextConnection)

TextCommand.ExecuteNonQuery()
TextConnection.Close()

End Function


Paul
~~~~
Microsoft MVP (Visual Basic)
 

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

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top