C# 倒出CSV文件 DataTable 自带的表头

#region DataGrid转CSV文件
/// <summary>
/// Export the data from datatable to CSV file
/// </summary>
/// <param name="grid">DataGrid</param>
public string ExportDataGridToCSV(DataTable dt)
{

  string path = null;
  //string strFile = "syncUserData" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";
  // path = HttpContext.Current.Server.MapPath(strFile);
  string strPath = "C://Temp//" + "mapData" + ".csv";//保存到本项目文件夹下
using (System.IO.FileStream fs = new FileStream(strPath, System.IO.FileMode.Create, System.IO.FileAccess.Write))
{

  using (StreamWriter sw = new StreamWriter(fs, new System.Text.UTF8Encoding()))
  {
  for (int i = 0; i < dt.Columns.Count - 1; i++)
    {
      sw.Write(dt.Columns[i].ColumnName);
      sw.Write(",");
    }
  sw.Write(dt.Columns[dt.Columns.Count - 1].ColumnName);
  sw.WriteLine("");
  for (int i = 0; i < dt.Rows.Count; i++)
  {
    for (int j = 0; j < dt.Columns.Count - 1; j++)
    {
      sw.Write(DelQuota(dt.Rows[i][j].ToString()));
      sw.Write(",");
    }
    sw.Write(DelQuota(dt.Rows[i][dt.Columns.Count - 1].ToString()));
    sw.WriteLine("");
  }
  sw.Flush();
  }

  }
  return path;
}

posted @ 2015-04-09 10:34  Kevin_Zhou_9  阅读(956)  评论(0编辑  收藏  举报