123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- 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
- {
- /// <summary>
- /// 从CSC文件读取信息
- /// </summary>
- /// <param name="tableName">文件路径名(需要有文件后缀)</param>
- /// <param name="headCount">表头</param>
- /// <returns></returns>
- public static List<T> ReadInfoFromCSV<T>(string filedPath, int headCount)
- {
- List<T> tmpMsg = new List<T>();
- 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;
- }
- /// <summary>
- /// 将数据信息写入到CSV文件中
- /// </summary>
- /// <typeparam name="T">类型</typeparam>
- /// <param name="ts">信息</param>
- /// <param name="path">路径</param>
- public static bool WriteInfoToCsv<T>(string path,List<T> 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;
- }
- }
|