博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

c#读取CSV

Posted on 2024-07-02 21:34  火冰·瓶  阅读(1)  评论(0编辑  收藏  举报
private void ReadCVS(YaJiangBigDataContext _content,Type classType, string csvPath)
        {                         
//YaJiangBigDataContext 是EF的Contex,本例中可以替换为List<Object>
//csvPath 必须完整的物理路径 //classType 是用来存放csv数据的类的type int rowIndex = 0; using (var reader = new StreamReader(File.OpenRead(csvPath))) { string[] title = Array.Empty<string>();//保存标题 while (!reader.EndOfStream) { var line = reader.ReadLine(); if (!string.IsNullOrEmpty(line)) { string[] data= line.Split("\t"); //分隔符为\t if (rowIndex == 0) { //标题行 title = data; } else { //内容行,每行创建一个对象存储数据 object myObj = Activator.CreateInstance(classType); for (int i = 0; i < title.Length; i++) { PropertyInfo propertyInfo = classType.GetProperty(title[i]);
Type pt
= propertyInfo.PropertyType;
propertyInfo.SetValue(myObj, propertyInfo.PropertyType.Name.Contains(
"Nullable") ? Convert.ChangeType(data[i], Nullable.GetUnderlyingType(pt)) : Convert.ChangeType(data[i], pt)); //给对象赋值,进行了Nullable判断和值类型转换 } _content.Add(myObj); //对象添加到EFContext中,也可以添加到List中 } } rowIndex++; } } }