C# .NET - convert DATATABLE to CSV in C# - Asked By muthuraman alexander on 17-Sep-11 03:01 AM

hi all,

i have a datatable ...
how can i convert that to a CSV file ...
i need help for this
any pls give me some about this

thanks
muthu
Riley K replied to muthuraman alexander on 17-Sep-11 03:45 AM
Use this method to convert datatabel to CSV


Just pass the dataTable and the Path where you want to create the CSV file

public void CreateCSVFile(DataTable dt, string strFilePath)
 
  {
    #region Export Grid to CSV
 
    // Create the CSV file to which grid data will be exported.
 
    StreamWriter sw = new StreamWriter(strFilePath, false);
 
    // First we will write the headers.
 
    //DataTable dt = m_dsProducts.Tables[0];
 
    int iColCount = dt.Columns.Count;
 
    for (int i = 0; i < iColCount; i++)
 
    {
 
      sw.Write(dt.Columns[i]);
 
      if (i < iColCount - 1)
 
      {
 
        sw.Write(",");
 
      }
 
    }
 
    sw.Write(sw.NewLine);
 
    // Now write all the rows.
 
    foreach (DataRow dr in dt.Rows)
 
    {
 
      for (int i = 0; i < iColCount; i++)
 
      {
 
        if (!Convert.IsDBNull(dr[i]))
 
        {
 
          sw.Write(dr[i].ToString());
 
        }
 
        if (i < iColCount - 1)
 
        {
 
          sw.Write(",");
 
        }
 
      }
 
      sw.Write(sw.NewLine);
 
    }
    sw.Close();
 
    #endregion
 
  }

Reena Jain replied to muthuraman alexander on 17-Sep-11 04:21 AM
Hi,

This is one of the easiest ways of exporting the data to excel.  The content of the DataTable should be written to the response by setting ContentType attribute to "application/vnd.ms-excel" and by setting its header.


protected void Button3_Click(object sender, EventArgs e)
 
  {
 
  DataTable dt = GetData();
 
  string attachment = "attachment; filename=Employee.xls";
 
  Response.ClearContent();
 
  Response.AddHeader("content-disposition", attachment);
 
  Response.ContentType = "application/vnd.ms-excel";
 
  string tab = "";
 
  foreach (DataColumn dc in dt.Columns)
 
  {
 
    Response.Write(tab + dc.ColumnName);
 
    tab = "\t";
 
  }
 
  Response.Write("\n");
 
  
 
  int i;
 
  foreach (DataRow dr in dt.Rows)
 
  {
 
    tab = "";
 
    for (i = 0; i < dt.Columns.Count; i++)
 
    {
 
    Response.Write(tab + dr[i].ToString());
 
    tab = "\t";
 
    }
 
    Response.Write("\n");
 
  }
 
  Response.End();
 
  }

Execute the page and see export to excel in action.


Hope this will help you
muthuraman alexander replied to Riley K on 17-Sep-11 06:34 AM
hi
thank u
your code works great

thanks a lot
Muthu
Riley K replied to muthuraman alexander on 17-Sep-11 12:53 PM
Welcome