1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| //write function public void writeDataCSV(string file_path, DataTable my_dt) { FileStream my_filestream; StreamWriter my_streamwriter; string my_data = null; if (!File.Exists(file_path)) { my_filestream = new FileStream(file_path, FileMode.Create, FileAccess.Write); my_streamwriter = new StreamWriter(my_filestream, Encoding.UTF8); //write columns name for (int i = 0; i < my_dt.Columns.Count; i++) { my_data += my_dt.Columns[i].ColumnName.ToString(); if (i < my_dt.Columns.Count - 1) { my_data += ","; } } my_streamwriter.WriteLine(my_data); } else { my_filestream = new FileStream(file_path, FileMode.Append, FileAccess.Write); my_streamwriter = new StreamWriter(my_filestream, Encoding.UTF8); } //write rows for (int i = 0; i < my_dt.Rows.Count; i++) { my_data = null; for (int j = 0; j < my_dt.Columns.Count; j++) { my_data += my_dt.Rows[i][j].ToString(); if (j < my_dt.Columns.Count - 1) { my_data += ","; } } my_streamwriter.WriteLine(my_data); } my_streamwriter.Close(); my_filestream.Close(); }
|