public static CSVFile LoadFromDataTable(DataTable DT, bool HasHeader = true) { CSVFile CSVF = new CSVFile(); if (HasHeader) { CSVLine L = new CSVLine(); foreach (DataColumn C in DT.Columns) { L.Columns.Add(C.ColumnName); } CSVF.Lines.Add(L); } foreach (DataRow R in DT.Rows) { CSVLine L = new CSVLine(); foreach (DataColumn C in DT.Columns) { L.Columns.Add(R[C.ColumnName].ToString()); } CSVF.Lines.Add(L); } return(CSVF); }
public static DataTable ImportToDataTable <tt>(FileInfo fileInfo, Dictionary <string, string> columnMapping = null) where tt : class { var file = CSVFile.LoadFromFile(fileInfo.FullName); var tp = typeof(tt); var item = (tt)tp.Assembly.CreateInstance(tp.FullName, true); CSVFile.CSVLine headerLine = null /* TODO Change to default(_) if this is not a reference type */; var headerLineNumber = 0; // Dim propList = item.GetPropertyNames() var cnt = 0; var fnd = false; while ((headerLineNumber == 0 && cnt < file.Lines.Count) && !fnd) { var line = file.Lines[cnt]; foreach (var col in line.Columns) { if ((item.DoesPropertyExist(col.Trim()) || (columnMapping != null && columnMapping.ContainsKey(col.Trim())))) { headerLine = line; headerLineNumber = cnt; fnd = true; } } cnt += 1; } Debug.WriteLine("Header Line Number = " + headerLineNumber); var table = file.ToDataTable(headerLine: headerLineNumber); return(table); }
public static CSVFile LoadFromFileData(StreamReader ReadFile, string ColDelimiter = ",") { CSVFile CSVF = new CSVFile(); CSVF.ColumnDelimiter = ColDelimiter; var parser = new CsvHelper.CsvReader(ReadFile, new CsvConfiguration(CultureInfo.CurrentCulture) { Delimiter = ColDelimiter }); while (parser.Read()) { var cols = new List <string>(); for (int a = 0; a < parser.ColumnCount; a++) { cols.Add(parser.GetField(a)); } CSVF.Lines.Add(new CSVLine(cols)); } return(CSVF); }