<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>

[{'answer_id': 44219, 'author': 'Simon Gillbee', 'author_id': 756, 'author_profile': 'https://Stackoverflow.com/users/756', 'pm_score': 6, 'selected': True, 'text': '<p>CSV formatting has some gotchas. Have you asked yourself these questions:</p>\n\n<ul>\n<li>Does any of my data have embedded commas?</li>\n<li>Does any of my data have embedded double-quotes?</li>\n<li>Does any of my data have have newlines?</li>\n<li>Do I need to support Unicode strings?</li>\n</ul>\n\n<p>I see several problems in your code above. The comma thing first of all... you are stripping commas:</p>\n\n<pre><code>CsvLine.Append(Format(b.Price, "c").Replace(",", ""))\n</code></pre>\n\n<p>Why? In CSV, you should be surrounding anything which has commas with quotes:</p>\n\n<pre><code>CsvLine.Append(String.Format("\\"{0:c}\\"", b.Price))\n</code></pre>\n\n<p>(or something like that... my VB is not very good). If you\'re not sure if there are commas, but put quotes around it. If there are quotes in the string, you need to escape them by doubling them. <code>"</code> becomes <code>""</code>.</p>\n\n<pre><code>b.Title.Replace("\\"", "\\"\\"")\n</code></pre>\n\n<p>Then surround this by quotes if you want. If there are newlines in your string, you need to surround the string with quotes... yes, literal newlines <em>are</em> allowed in CSV files. It looks weird to humans, but it\'s all good.</p>\n\n<p>A good CSV writer requires some thought. A good CSV reader (parser) is just plain hard (and no, regex not good enough for parsing CSV... it will only get you about 95% of the way there).</p>\n\n<p>And then there is Unicode... or more generally I18N (Internationalization) issues. For example, you are stripping commas out of a formatted price. But that\'s assuming the price is formatted as you expect it in the US. In France, the number formatting is reversed (periods used instead of commas, and <em>vice versa</em>). Bottom line, use culture-agnostic formatting wherever possible.</p>\n\n<p>While the issue here is <em>generating</em> CSV, inevitably you will need to parse CSV. In .NET, the best parser I have found (for free) is <a href="http://www.codeproject.com/KB/database/CsvReader.aspx" rel="noreferrer">Fast CSV Reader</a> on <a href="http://www.codeproject.com" rel="noreferrer">CodeProject</a>. I\'ve actually used it in production code and it is really really fast, and very easy to use!</p>\n'}, {'answer_id': 44237, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 3, 'selected': False, 'text': '<p>I pass all my CSV data through a function like this:</p>\n\n<pre><code>Function PrepForCSV(ByVal value As String) As String\n    return String.Format("""{0}""", Value.Replace("""", """"""))\nEnd Function\n</code></pre>\n\n<p>Also, if you\'re not serving up html you probably want an http handler (.as<strong>h</strong>x file) rather than a full web page.  If you create a new handler in Visual Studio, odds are you could just copy past your existing code into the main method and it will just work, with a small performance boost for your efforts.</p>\n'}, {'answer_id': 44257, 'author': 'Rob Pilkington', 'author_id': 1623, 'author_profile': 'https://Stackoverflow.com/users/1623', 'pm_score': 2, 'selected': False, 'text': '<p>In addition to what Simon said, you may want to read the <a href="http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm" rel="nofollow noreferrer">CSV how-to guide</a> and make sure your output doesn\'t run across any of the gotchas.</p>\n\n<p>To clarify something Simon said: </p>\n\n<blockquote>\n  <p>Then surround this by quotes if you want</p>\n</blockquote>\n\n<p>Fields that contain doubled up double quotes ("") will need to be completely surrounded with double quotes. There shouldn\'t be any harm in just wrapping all fields with double quotes, unless you specifically want the parser to strip out leading and trailing whitespace (instead of trimming it yourself).</p>\n'}, {'answer_id': 44316, 'author': 'Spoike', 'author_id': 3713, 'author_profile': 'https://Stackoverflow.com/users/3713', 'pm_score': 2, 'selected': False, 'text': '<p>If you want a colon delimited value converter then there is a 3rd party open source called <a href="http://filehelpers.sourceforge.net/" rel="nofollow noreferrer">FileHelpers</a>. I\'m not sure about what open-source license it is under, but it has helped me quite a lot.</p>\n'}, {'answer_id': 46493, 'author': 'Josh Hinman', 'author_id': 2527, 'author_profile': 'https://Stackoverflow.com/users/2527', 'pm_score': 2, 'selected': False, 'text': '<p>There\'s a lot of overhead associated with the Page class. Since you\'re just spitting out a CSV file and have no need for postback, server controls, caching, or the rest of it, you should make this into a handler with an .ashx extension. <a href="http://www.aspcode.net/Creating-an-ASHX-handler-in-ASPNET.aspx" rel="nofollow noreferrer">See here</a>.</p>\n'}, {'answer_id': 98123, 'author': 'Ricky Supit', 'author_id': 4191, 'author_profile': 'https://Stackoverflow.com/users/4191', 'pm_score': 2, 'selected': False, 'text': '<p>You can create the equivalent of bookString() in the query itself. Here is what I think would be a simpler way.  </p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n    using (var db = new bookDevelopmentDataContext())\n    {\n        string fileName = "book.csv";\n        var q = from b in db.books\n                select string.Format("{0:d},\\"{1}\\",\\"{2}\\",{3:F2}", b.Published, b.Title.Replace("\\"", "\\"\\""), b.Author.Replace("\\"", "\\"\\""), t.price);\n\n        string outstring = string.Join(",", q.ToArray());\n\n        Response.Clear();\n        Response.ClearHeaders();\n        Response.ContentType = "text/csv";\n        Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));\n        Response.Write("Published,Title,Author,Price," + outstring);\n        Response.End();\n    }\n}\n</code></pre>\n'}, {'answer_id': 4046459, 'author': 'Paul Mendoza', 'author_id': 29277, 'author_profile': 'https://Stackoverflow.com/users/29277', 'pm_score': 1, 'selected': False, 'text': '<p>I use the following method when building a CSV file from a DataTable. ControllerContext is just the reponse stream object where the file is written to. For you it is just going to be the Response object. </p>\n\n<pre><code>public override void ExecuteResult(ControllerContext context)\n        {\n            StringBuilder csv = new StringBuilder(10 * Table.Rows.Count * Table.Columns.Count);\n\n            for (int c = 0; c &lt; Table.Columns.Count; c++)\n            {\n                if (c &gt; 0)\n                    csv.Append(",");\n                DataColumn dc = Table.Columns[c];\n                string columnTitleCleaned = CleanCSVString(dc.ColumnName);\n                csv.Append(columnTitleCleaned);\n            }\n            csv.Append(Environment.NewLine);\n            foreach (DataRow dr in Table.Rows)\n            {\n                StringBuilder csvRow = new StringBuilder();\n                for(int c = 0; c &lt; Table.Columns.Count; c++)\n                {\n                    if(c != 0)\n                        csvRow.Append(",");\n\n                    object columnValue = dr[c];\n                    if (columnValue == null)\n                        csvRow.Append("");\n                    else\n                    {\n                        string columnStringValue = columnValue.ToString();\n\n\n                        string cleanedColumnValue = CleanCSVString(columnStringValue);\n\n                        if (columnValue.GetType() == typeof(string) &amp;&amp; !columnStringValue.Contains(","))\n                        {\n                            cleanedColumnValue = "=" + cleanedColumnValue; // Prevents a number stored in a string from being shown as 8888E+24 in Excel. Example use is the AccountNum field in CI that looks like a number but is really a string.\n                        }\n                        csvRow.Append(cleanedColumnValue);\n                    }\n                }\n                csv.AppendLine(csvRow.ToString());\n            }\n\n            HttpResponseBase response = context.HttpContext.Response;\n            response.ContentType = "text/csv";\n            response.AppendHeader("Content-Disposition", "attachment;filename=" + this.FileName);\n            response.Write(csv.ToString());\n        }\n\n        protected string CleanCSVString(string input)\n        {\n            string output = "\\"" + input.Replace("\\"", "\\"\\"").Replace("\\r\\n", " ").Replace("\\r", " ").Replace("\\n", "") + "\\"";\n            return output;\n        }\n</code></pre>\n'}, {'answer_id': 18404453, 'author': 'blalond', 'author_id': 536625, 'author_profile': 'https://Stackoverflow.com/users/536625', 'pm_score': 1, 'selected': False, 'text': '<p>Looking mostly good except in your function "BookString()" you should pass all those strings through a small function like this first:</p>\n\n<pre><code>Private Function formatForCSV(stringToProcess As String) As String\n    If stringToProcess.Contains("""") Or stringToProcess.Contains(",") Then\n        stringToProcess = String.Format("""{0}""", stringToProcess.Replace("""", """"""))\n    End If\n    Return stringToProcess\nEnd Function\n\n\'So, lines like this:\nCsvLine.Append(b.Title.Replace(",", "") + ",")\n\'would be lines like this instead:\nCsvLine.Append(formatForCSV(b.Title)) + ",")\n</code></pre>\n\n<p>The function will format your strings well for CSV. It replaces quotes with double quotes and add quotes around the string if there are either quotes or commas in the string. </p>\n\n<p>Note that it doesn\'t account for newlines, but can only safely guarantee good CSV output for those strings that you know are free of newlines (inputs from simple one-line text forms, etc.).</p>\n'}]
['https://Stackoverflow.com/questions/44194', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83/']