随笔 - 165, 文章 - 0, 评论 - 18, 阅读 - 22万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

c#读取CSV

Posted on   火冰·瓶  阅读(51)  评论(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++; } } }
复制代码

 

相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示