Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I best generate a CSV (comma-delimited text file) for download with ASP.NET?
    primarykey
    data
    text
    <p>This is what I've got. It works. But, is there a simpler or better way?</p> <p>One an ASPX page, I've got the download link...</p> <pre><code>&lt;asp:HyperLink ID="HyperLinkDownload" runat="server" NavigateUrl="~/Download.aspx"&gt;Download as CSV file&lt;/asp:HyperLink&gt; </code></pre> <p>And then I've got the Download.aspx.vb Code Behind...</p> <pre><code>Public Partial Class Download Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'set header Response.Clear() Response.ContentType = "text/csv" Dim FileName As String = "books.csv" Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName) 'generate file content Dim db As New bookDevelopmentDataContext Dim Allbooks = From b In db.books _ Order By b.Added _ Select b Dim CsvFile As New StringBuilder CsvFile.AppendLine(CsvHeader()) For Each b As Book In Allbooks CsvFile.AppendLine(bookString(b)) Next 'write the file Response.Write(CsvFile.ToString) Response.End() End Sub Function CsvHeader() As String Dim CsvLine As New StringBuilder CsvLine.Append("Published,") CsvLine.Append("Title,") CsvLine.Append("Author,") CsvLine.Append("Price") Return CsvLine.ToString End Function Function bookString(ByVal b As Book) As String Dim CsvLine As New StringBuilder CsvLine.Append(b.Published.ToShortDateString + ",") CsvLine.Append(b.Title.Replace(",", "") + ",") CsvLine.Append(b.Author.Replace(",", "") + ",") CsvLine.Append(Format(b.Price, "c").Replace(",", "")) Return CsvLine.ToString End Function End Class </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload