Travis Laborde Blog

play boxing daddy?

producing CSV files on the fly

Two people recently have asked me how to produce this sort of output from ASP.NET.  Please note, the code here is not meant to be an example of any best practices.  There are plenty of things that could (should) be done a bit differently.  The listing is for the express purpose of showing how to simply get it done.  Doing it the “right“ way is up to you :)

What isn't shown here is the code to get your ADO.NET DataTable object from your database.  Assuming that you have your DataTable, what you need to do is turn that into a string, and send that string to the browser in such a way that the browser opens it in a “new“ window, in Excel or whatever application the user has configured to load .CSV files with.

What also isn't shown here is how you'd “get to“ this page.  On any other page in your application, you could have a button whose click event will do a simple Server.Transfer to this page.  Or anything like that.

The thing to remember, is “you don't need anything at all in your Webform.“  Just leave it blank.

I hope someone can make use of this.

Travis

 

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Response.ContentType = ""

Response.AppendHeader("Content-Disposition", "inline;filename=filename.csv")

Response.Write(GetCSV(myDataTable))

Response.End()

End Sub

Private Function GetCSV(ByVal dt As DataTable) As String

Dim sb As New System.Text.StringBuilder

Dim rowCounter, colCounter As Integer

'first the row with fieldnames

For colCounter = 0 To dt.Columns.Count - 1

sb.Append(Chr(34))

sb.Append(dt.Columns(colCounter).ColumnName)

sb.Append(Chr(34))

sb.Append(",")

Next

sb.Append(vbCrLf)

'then the rows of data

For rowCounter = 0 To dt.Rows.Count - 1

For colCounter = 0 To dt.Columns.Count - 1

If Not IsDBNull(dt.Rows(rowCounter).Item(colCounter)) Then

If Not IsNumeric(dt.Rows(rowCounter).Item(colCounter)) Then

sb.Append(Chr(34))

End If

sb.Append(dt.Rows(rowCounter).Item(colCounter))

If Not IsNumeric(dt.Rows(rowCounter).Item(colCounter)) Then

sb.Append(Chr(34))

End If

Else

'sb.Append(Chr(34) & Chr(34))

End If

If colCounter <> dt.Columns.Count - 1 Then

sb.Append(",")

End If

Next

sb.Append(vbCrLf)

Next

Return sb.ToString

End Function

Legacy Comments


anon
2004-04-22
re: producing CSV files on the fly
try using it in a dataset and using a for each loop instead
pseudocode:
for each datarow in datasettablesrows
for each item in datarow.itemarray
add comma
end for
end for

erik
2006-04-13
re: producing CSV files on the fly
Excellent example. This is just what I was looking for so that I wouldn't have to create the file on the server and then stream it to the client.