We Recommend

Accelerated C# 2008 Accelerated C# 2008
This book is both a rapid tutorial and a permanent reference. You’ll quickly master C# syntax while learning how the CLR simplifies many programming tasks. You’ll also learn best practices that ensure your code will be efficient, reusable, and robust. Why spend months or years discovering the best ways to design and code C# when this book will show you how to do things the right way, right from the start?


Posted By

krisdb on 06/18/08


Tagged

c-sharp


Versions (?)


Who likes this?

1 person has marked this snippet as a favorite

ad5qa


outputCSV


Published in: C# 


  1. protected void outputCSV(DataTable dtResults)
  2. {
  3. bool boolFirstItem = true; // Whether this is the first item in the data
  4.  
  5. // Set the output to the an Excel CSV (Comma Seperated Value) file
  6. Response.AppendHeader("content-disposition", "attachment; filename=RegistrationUsersExport.csv");
  7. Response.ContentType = "application/vnd.ms-excel";
  8.  
  9. // Output the Column Names
  10. for (int i = 0; i < dtResults.Columns.Count; i++)
  11. {
  12. // Handle placing commas between the items
  13. if (boolFirstItem)
  14. boolFirstItem = false;
  15. else
  16. Response.Write(",");
  17.  
  18. // Output the column name
  19. Response.Write(dtResults.Columns[i].ColumnName);
  20. }
  21. Response.Write("\n");
  22.  
  23.  
  24. // Read the data and export the values
  25. foreach (DataRow drResults in dtResults.Rows)
  26. {
  27. // Output the Column Values
  28. boolFirstItem = true;
  29. for (int i = 0; i < dtResults.Columns.Count; i++)
  30. {
  31. // Handle placing commas between the items
  32. if (boolFirstItem)
  33. boolFirstItem = false;
  34. else
  35. Response.Write(",");
  36.  
  37. // Output the column value
  38. Response.Write("\"" + drResults[i].ToString() + "\"");
  39. }
  40. Response.Write("\n");
  41. }
  42.  
  43. Response.End();
  44. }

Report this snippet 

You need to login to post a comment.