code_junkie

How do I best generate a CSV (comma-delimited text file) for download with ASP.NET?

Nov 10th, 2011
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.73 KB | None | 0 0
  1. <asp:HyperLink ID="HyperLinkDownload" runat="server" NavigateUrl="~/Download.aspx">Download as CSV file</asp:HyperLink>
  2.  
  3. Public Partial Class Download
  4. Inherits System.Web.UI.Page
  5.  
  6. Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  7. 'set header
  8. Response.Clear()
  9. Response.ContentType = "text/csv"
  10. Dim FileName As String = "books.csv"
  11. Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName)
  12.  
  13. 'generate file content
  14. Dim db As New bookDevelopmentDataContext
  15. Dim Allbooks = From b In db.books _
  16. Order By b.Added _
  17. Select b
  18. Dim CsvFile As New StringBuilder
  19. CsvFile.AppendLine(CsvHeader())
  20. For Each b As Book In Allbooks
  21. CsvFile.AppendLine(bookString(b))
  22. Next
  23.  
  24. 'write the file
  25. Response.Write(CsvFile.ToString)
  26. Response.End()
  27. End Sub
  28.  
  29. Function CsvHeader() As String
  30. Dim CsvLine As New StringBuilder
  31. CsvLine.Append("Published,")
  32. CsvLine.Append("Title,")
  33. CsvLine.Append("Author,")
  34. CsvLine.Append("Price")
  35. Return CsvLine.ToString
  36. End Function
  37.  
  38. Function bookString(ByVal b As Book) As String
  39. Dim CsvLine As New StringBuilder
  40. CsvLine.Append(b.Published.ToShortDateString + ",")
  41. CsvLine.Append(b.Title.Replace(",", "") + ",")
  42. CsvLine.Append(b.Author.Replace(",", "") + ",")
  43. CsvLine.Append(Format(b.Price, "c").Replace(",", ""))
  44. Return CsvLine.ToString
  45. End Function
  46.  
  47. End Class
  48.  
  49. CsvLine.Append(Format(b.Price, "c").Replace(",", ""))
  50.  
  51. CsvLine.Append(String.Format(""{0:c}"", b.Price))
  52.  
  53. b.Title.Replace(""", """")
  54.  
  55. Function PrepForCSV(ByVal value As String) As String
  56. return String.Format("""{0}""", Value.Replace("""", """"""))
  57. End Function
  58.  
  59. protected void Page_Load(object sender, EventArgs e)
  60. {
  61. using (var db = new bookDevelopmentDataContext())
  62. {
  63. string fileName = "book.csv";
  64. var q = from b in db.books
  65. select string.Format("{0:d},"{1}","{2}",{3:F2}", b.Published, b.Title.Replace(""", """"), b.Author.Replace(""", """"), t.price);
  66.  
  67. string outstring = string.Join(",", q.ToArray());
  68.  
  69. Response.Clear();
  70. Response.ClearHeaders();
  71. Response.ContentType = "text/csv";
  72. Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));
  73. Response.Write("Published,Title,Author,Price," + outstring);
  74. Response.End();
  75. }
  76. }
  77.  
  78. public override void ExecuteResult(ControllerContext context)
  79. {
  80. StringBuilder csv = new StringBuilder(10 * Table.Rows.Count * Table.Columns.Count);
  81.  
  82. for (int c = 0; c < Table.Columns.Count; c++)
  83. {
  84. if (c > 0)
  85. csv.Append(",");
  86. DataColumn dc = Table.Columns[c];
  87. string columnTitleCleaned = CleanCSVString(dc.ColumnName);
  88. csv.Append(columnTitleCleaned);
  89. }
  90. csv.Append(Environment.NewLine);
  91. foreach (DataRow dr in Table.Rows)
  92. {
  93. StringBuilder csvRow = new StringBuilder();
  94. for(int c = 0; c < Table.Columns.Count; c++)
  95. {
  96. if(c != 0)
  97. csvRow.Append(",");
  98.  
  99. object columnValue = dr[c];
  100. if (columnValue == null)
  101. csvRow.Append("");
  102. else
  103. {
  104. string columnStringValue = columnValue.ToString();
  105.  
  106.  
  107. string cleanedColumnValue = CleanCSVString(columnStringValue);
  108.  
  109. if (columnValue.GetType() == typeof(string) && !columnStringValue.Contains(","))
  110. {
  111. 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.
  112. }
  113. csvRow.Append(cleanedColumnValue);
  114. }
  115. }
  116. csv.AppendLine(csvRow.ToString());
  117. }
  118.  
  119. HttpResponseBase response = context.HttpContext.Response;
  120. response.ContentType = "text/csv";
  121. response.AppendHeader("Content-Disposition", "attachment;filename=" + this.FileName);
  122. response.Write(csv.ToString());
  123. }
  124.  
  125. protected string CleanCSVString(string input)
  126. {
  127. string output = """ + input.Replace(""", """").Replace("rn", " ").Replace("r", " ").Replace("n", "") + """;
  128. return output;
  129. }
Add Comment
Please, Sign In to add comment