public static CsvData ObjectToCsvData(object obj) { CsvData csvData = CsvData.Create(); Type t = obj.GetType(); if (!typeof(IEnumerable).IsAssignableFrom(t)) { throw new ArgumentException("对象没有实现IEnumerable"); } //build header FieldInfo[] obj_fields = t.GetFields(); foreach (var field in obj_fields) { csvData.Header.Add(field.Name); } var obj_props = t.GetProperties(); foreach (PropertyInfo prop in obj_props) { csvData.Header.Add(prop.Name); } //build body IEnumerable enumerable = (IEnumerable)obj; IEnumerator record_it = enumerable.GetEnumerator(); while (record_it.MoveNext()) { object item = record_it.Current; if (item == null) { continue; } //行内数据 List <string> recordBuilder = new List <string>(); Type itemType = item.GetType(); FieldInfo[] fields = itemType.GetFields(); foreach (FieldInfo field in fields) { string recordItem = field.GetValue(item).ToString(); recordBuilder.Add(recordItem); } PropertyInfo[] propInfos = itemType.GetProperties(); foreach (PropertyInfo prop in propInfos) { string recordItem = prop.GetValue(item, null).ToString(); recordBuilder.Add(recordItem); } csvData.InsertData(recordBuilder.ToArray()); } return(csvData); }
public static CsvData Read(string csv) { Reset(); csvContent = csv; //行 列 List <List <string> > dataTable = new List <List <string> >(); List <string> recordData = new List <string>(); dataTable.Add(recordData); string token = null; while ((token = GetToken()) != null) { //换行增加新纪录 if (token == LFSTR) { recordData = new List <string>(); dataTable.Add(recordData); } else { recordData.Add(token); } } //移除所有尾部空行 for (int i = dataTable.Count - 1; i >= 0; i--) { if (dataTable[i].Count == 0) { dataTable.RemoveAt(i); } else { break; } } List <string> header = null; if (dataTable.Count > 1) { header = dataTable[0]; } CsvData csvData = CsvData.Create(header); for (int i = 1; i < dataTable.Count; i++) { csvData.InsertData(dataTable[i].ToArray()); } return(csvData); }