1.)首先 所在頁面的 命名空間請加入 Using 內.
2.)CLASS
public static class DataTABLE_TO_CSV_CLASS
{
public static string DT_TO_CSV(this DataTable dt)
{
StringBuilder sb = new StringBuilder();
for (int x = 0; x < dt.Columns.Count; x++)
{
if (x != 0)
sb.Append(",");
sb.Append(dt.Columns[x].ColumnName);
}
sb.AppendLine();
foreach (DataRow row in dt.Rows)
{
for (int x = 0; x < dt.Columns.Count; x++)
{
if (x != 0)
sb.Append(",");
sb.Append(row[dt.Columns[x]].ToString());
}
sb.AppendLine();
}
return sb.ToString();
}
}
使用時:
//將 Datatable 存成 CSV
string ds_string = DataTABLE_TO_CSV_CLASS.DT_TO_CSV(ds._DT_ReturnValue);
ds_string = ds_string.Replace("\r\n","\n").Trim();
string[] ds_string_array=ds_string.Split(new char[] { '\n'});
File.WriteAllLines(System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory).ToString()+"\\"+txtStartDate.Text+"-OQC.csv", ds_string_array, Encoding.Default);
沒有留言:
張貼留言