PROWAREtech

articles » archived » asp-net » csv-output

ASP.NET: CSV Output

Comma-separated value output for use by Excel or other spreadsheet application (.NET Framework).

This code will connect to the MS SQL Server pubs database, open the titles table, and output the results as a CSV file using Response.Write() and the browser will save the file as titles.csv.

<%@ Page Language="VB" ContentType="text/csv" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Configuration" %>
<%
	Response.Clear()
	'tell the browser to save the file as titles.csv
	Response.AppendHeader("content-disposition", "attachment;filename=titles.csv")
	Dim oCon As New OleDbConnection(System.Configuration.ConfigurationManager.ConnectionStrings("ConnectPubs").ToString())
	oCon.Open()
	'FROM THE pubs DATABASE IN MS SQL SERVER
	Dim oCmd As New OleDbCommand("SELECT authors.au_lname, authors.au_fname, titles.title, titles.price," & _
	" titles.ytd_sales FROM titleauthor INNER JOIN titles ON titleauthor.title_id = titles.title_id INNER" & _
	" JOIN authors ON titleauthor.au_id = authors.au_id", oCon)
	Dim oRdr As OleDbDataReader = oCmd.ExecuteReader()
	Response.Write("LastName,FirstName,Title,Price,YTDSales" & ControlChars.CrLf)
	Do While oRdr.Read()
		Dim i As Integer = 0
		While i < oRdr.FieldCount
			Response.Write(IIf(i = 0, "", ",") & """" & IIf(IsDBNull(oRdr(i)), "", _
			oRdr(i).ToString().Replace("""", """""")) & """")
			i += 1
		End While
		Response.Write(ControlChars.CrLf)
	Loop
	oRdr.Close()
	oCon.Close()
	Response.End()
%>

PROWAREtech

Hello there! How can I help you today?
Ask any question

PROWAREtech

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE