Простой метод записи данных в формате DataTable или DataView на C# в CSV-файл.
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
using System; using System.Data; using System.Windows.Forms; using System.IO; private void ExportDatatviewToCsv(string iFilename, DataView dv) { // Open output stream StreamWriter swFile = new StreamWriter(iFilename); // Header string[] colLbls = new string[dv.Table.Columns.Count]; for (int i = 0; i < dv.Table.Columns.Count; i++) { colLbls[i] = dv.Table.Columns[i].ColumnName; colLbls[i] = GetWriteableValueForCsv(colLbls[i]); } // Write labels swFile.WriteLine(string.Join(",", colLbls)); // Rows of Data foreach (DataRowView rowData in dv) { string[] colData = new string[dv.Table.Columns.Count]; for (int i = 0; i < dv.Table.Columns.Count; i++) { object obj = rowData[i]; colData[i] = GetWriteableValueForCsv(obj); } // Write data in row swFile.WriteLine(string.Join(",", colData)); } // Close output stream swFile.Close(); } private void ExportDatatableToCsv(string iFilename, DataTable dt) { // Open output stream StreamWriter swFile = new StreamWriter(iFilename); // Header string[] colLbls = new string[dt.Columns.Count]; for (int i = 0; i < dt.Columns.Count; i++) { colLbls[i] = dt.Columns[i].ColumnName; colLbls[i] = GetWriteableValueForCsv(colLbls[i]); } // Write labels swFile.WriteLine(string.Join(",", colLbls)); // Rows of Data foreach (DataRow rowData in dt.Rows) { string[] colData = new string[dt.Columns.Count]; for (int i = 0; i < dt.Columns.Count; i++) { object obj = rowData[i]; colData[i] = GetWriteableValueForCsv(obj); } // Write data in row swFile.WriteLine(string.Join(",", colData)); } // Close output stream swFile.Close(); } public static string GetWriteableValueForCsv(object obj) { // Nullable types to blank if (obj == null || obj == Convert.DBNull) return ""; // if string has no ',' if (obj.ToString().IndexOf(",") == -1) return obj.ToString(); // remove backslahes return "\"" + obj.ToString() + "\""; } |