Exporting datatables to CSV

One thing I often find myself doing is writing code allowing data to be exported to CSV files so that clients can download it, and create reports using an application like Excel. Here’s a small class to make the process a little easier, which I thought might be helpful to other developers.

public class Exporter
{
 private DataTable m_DataTable;
 private string m_Filename;
 public Exporter()
 {
 }
 public DataTable Source
 {
  set { m_DataTable = value; }
 }
 public string Filename
 {
  set { m_Filename = value;  }
  get { return m_Filename;   }
 }
 public void Export()
 {
  if (m_DataTable == null) throw (new NullReferenceException("Datasource"));
  if (m_Filename == null) throw (new NullReferenceException("Filename"));
  string Header = string.Format("attachment;filename={0}", m_Filename);
  string Data = ConvertToCSV();
  System.Web.HttpContext.Current.Response.ClearHeaders();
  System.Web.HttpContext.Current.
     Response.AddHeader("Content-disposition", Header);
  System.Web.HttpContext.Current.Response.Write(Data);
  System.Web.HttpContext.Current.Response.End();
 }
 private string ConvertToCSV()
 {
  StringBuilder SB = new StringBuilder();
  foreach (DataColumn column in m_DataTable.Columns)
  {
   SB.Append(string.Format("{0},", column.ColumnName));
  }
  SB.Append("\n");
  foreach (DataRow row in m_DataTable.Rows)
  {
   foreach (DataColumn column in m_DataTable.Columns)
   {
    SB.Append(string.Format("\"{0}\",", row[column].ToString()));
   }
   SB.Append("\n");
  }
  SB.Append("\n");
  return (SB.ToString());
 }
}

Usage:

Exporter CSVExporter = new Exporter();
CSVExporter.Source = myDataTable;
CSVExporter.Filename = "ExportedData.CSV";
CSVExporter.Export();

This entry was posted in Uncategorized by Mun. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*