C#一个简单的解析csv文件的方法

可以将csv转成具体的类型对象,没有用序列化,需要传入转成函数手动编写类型转换代码,代码比较简单

        public class Model {
            public int 序号 { get; set; }
            public string 名称 { get; set; }
            public int 分数 { get; set; }
            public DateTime 日期 { get; set; }
        }
        void Test(string csvPath) {
            List<Model> list = ParseCSV(csvPath, row => new Model() {
                序号 = Convert.ToInt32(row["序号"]),
                名称 = row["名称"].ToString(),
                分数 = Convert.ToInt32(row["分数"]),
                日期 = Convert.ToDateTime(row["日期"])
            });
            Console.WriteLine($"解析数据{list.Count}条");
        }
        /// <summary>
        /// 解析csv
        /// </summary>
        /// <typeparam name="T">要转换的数据类型</typeparam>
        /// <param name="path">csv的文件路径</param>
        /// <param name="func">将csv数据转成具体对象的函数</param>
        /// <returns></returns>
        public static List<T> ParseCSV<T>(string path, Func<Dictionary<string, string>, T> func) {
            string[] column = null;
            List<T> list = new List<T>();
            Dictionary<string, string> dict = new Dictionary<string, string>();
            using (var fs = new FileStream(path, FileMode.Open)) {
                using (StreamReader sr = new StreamReader(fs)) {
                    bool isFirst = true;
                    while (true) {
                        string str = sr.ReadLine();
                        if (str != null) {
                            if (isFirst) {
                                column = str.Split(','); //第一次读取的是列
                                isFirst = false;
                            } else {
                                dict.Clear(); //将行封装成字典是为了让外面的操作更加简单清晰,避免用索引一个不小心整错了
                                string[] row = str.Split(',');
                                for (int i = 0; i < row.Length; i++) {
                                    dict.Add(column[i], row[i]);
                                }
                                list.Add(func(dict)); //本来打算用序列化自动处理的,但是感觉太麻烦了,还是通过传入转换函数手动转换吧
                            }
                        } else {
                            break;
                        }
                    }
                }
            }
            return list;
        }

 

posted @ 2022-10-08 11:50  WmW  阅读(592)  评论(0编辑  收藏  举报