using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEngine; using System.IO; using System.Linq; using TMPro; public class CSVHelper { /// /// 从CSC文件读取信息 /// /// 文件路径名(需要有文件后缀) /// 表头 /// public static List ReadInfoFromCSV(string filedPath, int headCount) { List tmpMsg = new List(); if (!File.Exists(filedPath)) { Debug.LogError($"{filedPath}不存在"); return null; } string config = File.ReadAllText(filedPath); if (!string.IsNullOrEmpty(config)) { string[] tmpLines = config.Split('\n'); for (int i = 1; i < tmpLines.Length; i++) { if (string.IsNullOrEmpty(tmpLines[i])) continue; if (tmpLines[i].Contains('\r')) tmpLines[i] = tmpLines[i].Replace("\r", ""); string[] columns = tmpLines[i].Split(','); FieldInfo[] tmpFieldInfos = typeof(T).GetFields(); if (tmpFieldInfos.Length != columns.Length) { Debug.LogError(string.Format($"请检查{typeof(T).Name}与表格{filedPath}元素数量是否相同!!!!")); return null; } object tmpT = Activator.CreateInstance(typeof(T)); for (int j = 0; j < tmpFieldInfos.Length; j++) { FieldInfo tmpFieldInfo = tmpFieldInfos[j]; tmpFieldInfo.SetValue(tmpT, columns[j].ToString()); } tmpMsg.Add((T)tmpT); } } return tmpMsg; } /// /// 将数据信息写入到CSV文件中 /// /// 类型 /// 信息 /// 路径 public static bool WriteInfoToCsv(string path,List ts) { bool tmpResult = false ; using (FileStream fs = new FileStream(path, FileMode.Create)) { using (StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8)) { string tmpHead = string.Empty; FieldInfo[] tmpFieldInfos = typeof(T).GetFields(); for (int i = 0;i < tmpFieldInfos.Length; i++) { tmpHead += tmpFieldInfos[i].Name; if (i < tmpFieldInfos.Length - 1) tmpHead += ","; } sw.WriteLine(tmpHead); for (int i = 0; i < ts.Count; i++) { string operationInfo = string.Empty; for (int j = 0;j < tmpFieldInfos.Length; j++) { operationInfo += tmpFieldInfos[j].GetValue(ts[i]).ToString(); if (j < tmpFieldInfos.Length - 1) operationInfo += ","; } if (i == ts.Count - 1) sw.Write(operationInfo); else sw.WriteLine(operationInfo); } } } tmpResult = true; return tmpResult; } }