linqtocsv文件有不太好的地方就是:无法设置标题的行数,默认首行就是标题,这不是很尴尬吗?   并不是所有的csv文件严格写的首行是标题,下面全是数据,我接受的任务就是读取很多.csv报表数据,里面就有很多前几行是说明性内容,下面才是标题和数据。为了更好的解决这个问题,自己写吧...

  本博客没有照搬linqtocsv全部源码,保留了主要功能,并对其优化,为我所用,哈哈...

  

  下面是主要代码:

  1-主文件CsvHelper:

  这里在独自解析数据的时候,遇到了很多坑:

  a-遇到数据含有分隔符的问题的解决办法,代码已经包含了

  b-遇到了解析源文档数据时,未指定字符编码时,部分数据丢失导致csv文件个别行数据解析异常的问题,针对该问题,就是老老实实把读取文件时加了字符编码的参数进去,默认UTF-8。  

  1. using Microsoft.Extensions.Logging;
  2. using PaymentAccountAPI.Helper;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Text;
  9.  
  10. namespace PaymentAccountAPI.CSV
  11. {
  12. public class CsvHelper
  13. {
  14. /// <summary>
  15. /// 日志
  16. /// </summary>
  17. private ILogger _Logger { get; set; }
  18.  
  19. public CsvHelper(ILogger<CsvHelper> logger)
  20. {
  21. this._Logger = logger;
  22. }
  23.  
  24. public List<T> Read<T>(string filePath, CsvFileDescription fileDescription) where T : class, new()
  25. {
  26. List<T> tList = new List<T>( * );
  27.  
  28. T t = null;
  29. int currentRawIndex = ;
  30.  
  31. if (File.Exists(filePath))
  32. {
  33. using (StreamReader streamReader = new StreamReader(filePath, fileDescription.Encoding))
  34. {
  35. Dictionary<int, FieldMapper> fieldMapperDic = FieldMapper.GetModelFieldMapper<T>().ToDictionary(m => m.CSVTitleIndex);
  36. string rawValue = null;
  37. string[] rawValueArray = null;
  38. PropertyInfo propertyInfo = null;
  39. string propertyValue = null;
  40. bool rawReadEnd = false;
  41.  
  42. bool isExistSplitChart = false;
  43. do
  44. {
  45. rawValue = streamReader.ReadLine();
  46.  
  47. //标题行
  48. if (currentRawIndex > fileDescription.TitleRawIndex)
  49. {
  50. if (!string.IsNullOrEmpty(rawValue))
  51. {
  52. //替换字符串含有分隔符为{分隔符},最后再替换回来
  53. if (rawValue.Contains("\""))
  54. {
  55. isExistSplitChart = true;
  56.  
  57. int yhBeginIndex = ;
  58. int yhEndIndex = ;
  59. string yhText = null;
  60. do
  61. {
  62. yhBeginIndex = StringHelper.GetIndexOfStr(rawValue, "\"", );
  63. yhEndIndex = StringHelper.GetIndexOfStr(rawValue, "\"", );
  64. yhText = rawValue.Substring(yhBeginIndex, (yhEndIndex - yhBeginIndex + ));
  65. string newYHText = yhText.Replace("\"", "").Replace(fileDescription.SeparatorChar.ToString(), "{分隔符}");
  66. rawValue = rawValue.Replace(yhText, newYHText);
  67. } while (rawValue.Contains("\""));
  68. }
  69.  
  70. rawValueArray = rawValue.Split(fileDescription.SeparatorChar);
  71.  
  72. t = new T();
  73. foreach (var fieldMapper in fieldMapperDic)
  74. {
  75. propertyInfo = fieldMapper.Value.PropertyInfo;
  76. propertyValue = rawValueArray[fieldMapper.Key - ];
  77. if (!string.IsNullOrEmpty(propertyValue))
  78. {
  79. try
  80. {
  81. if (isExistSplitChart && propertyValue.Contains("{分隔符}"))
  82. {
  83. propertyValue = propertyValue.Replace("{分隔符}", fileDescription.SeparatorChar.ToString());
  84. }
  85.  
  86. TypeHelper.SetPropertyValue(t, propertyInfo.Name, propertyValue);
  87. }
  88. catch (Exception e)
  89. {
  90. this._Logger.LogWarning(e, $"第{currentRawIndex + 1}行数据{propertyValue}转换属性{propertyInfo.Name}-{propertyInfo.PropertyType.Name}失败!");
  91. continue;
  92. }
  93. }
  94. }
  95. tList.Add(t);
  96. }
  97. else
  98. {
  99. rawReadEnd = true;
  100. }
  101. }
  102. currentRawIndex++;
  103. } while (rawReadEnd == false);
  104. }
  105. }
  106.  
  107. return tList;
  108. }
  109.  
  110. public void WriteFile<T>(string path, List<T> tList, CsvFileDescription fileDescription) where T : class, new()
  111. {
  112. if (!string.IsNullOrEmpty(path))
  113. {
  114. string fileDirectoryPath = null;
  115. if (path.Contains("\\"))
  116. {
  117. fileDirectoryPath = path.Substring(, path.LastIndexOf('\\'));
  118. }
  119. else
  120. {
  121. fileDirectoryPath = path.Substring(, path.LastIndexOf('/'));
  122. }
  123. if (!Directory.Exists(fileDirectoryPath))
  124. {
  125. Directory.CreateDirectory(fileDirectoryPath);
  126. }
  127.  
  128. int dataCount = tList.Count;
  129. Dictionary<int, FieldMapper> fieldMapperDic = FieldMapper.GetModelFieldMapper<T>().ToDictionary(m => m.CSVTitleIndex);
  130. int titleCount = fieldMapperDic.Keys.Max();
  131. string[] rawValueArray = new string[titleCount];
  132. StringBuilder rawValueBuilder = new StringBuilder();
  133. string rawValue = null;
  134. T t = null;
  135. PropertyInfo propertyInfo = null;
  136. int currentRawIndex = ;
  137. int tIndex = ;
  138.  
  139. using (StreamWriter streamWriter = new StreamWriter(path, false, fileDescription.Encoding))
  140. {
  141. do
  142. {
  143. try
  144. {
  145. rawValue = "";
  146.  
  147. #if DEBUG
  148. if (currentRawIndex % == )
  149. {
  150. this._Logger.LogInformation($"已写入文件:{path},数据量:{currentRawIndex}");
  151. }
  152. #endif
  153.  
  154. if (currentRawIndex >= fileDescription.TitleRawIndex)
  155. {
  156. //清空数组数据
  157. for (int i = ; i < titleCount; i++)
  158. {
  159. rawValueArray[i] = "";
  160. }
  161.  
  162. if (currentRawIndex > fileDescription.TitleRawIndex)
  163. {
  164. t = tList[tIndex];
  165. tIndex++;
  166. }
  167. foreach (var fieldMapperItem in fieldMapperDic)
  168. {
  169. //写入标题行
  170. if (currentRawIndex == fileDescription.TitleRawIndex)
  171. {
  172. rawValueArray[fieldMapperItem.Key - ] = fieldMapperItem.Value.CSVTitle;
  173. }
  174. //真正的数据从标题行下一行开始写
  175. else
  176. {
  177. propertyInfo = fieldMapperItem.Value.PropertyInfo;
  178. object propertyValue = propertyInfo.GetValue(t);
  179. string formatValue = null;
  180. if (propertyValue != null)
  181. {
  182. if (propertyInfo.PropertyType is IFormattable && !string.IsNullOrEmpty(fieldMapperItem.Value.OutputFormat))
  183. {
  184. formatValue = ((IFormattable)propertyValue).ToString(fieldMapperItem.Value.OutputFormat, null);
  185. }
  186. else
  187. {
  188. formatValue = propertyValue.ToString();
  189. }
  190.  
  191. //如果属性值含有分隔符,则使用双引号包裹
  192. if (formatValue.Contains(fileDescription.SeparatorChar.ToString()))
  193. {
  194. formatValue = $"\"{formatValue}\"";
  195. }
  196. rawValueArray[fieldMapperItem.Key - ] = formatValue;
  197. }
  198. }
  199. }
  200. rawValue = string.Join(fileDescription.SeparatorChar, rawValueArray);
  201. }
  202. rawValueBuilder.Append(rawValue + "\r\n");
  203. }
  204. catch (Exception e)
  205. {
  206. this._Logger.LogWarning(e, $"(异常)Excel第{currentRawIndex+1}行,数据列表第{tIndex + 1}个数据写入失败!rawValue:{rawValue}");
  207. throw;
  208. }
  209.  
  210. currentRawIndex++;
  211. } while (tIndex < dataCount);
  212. streamWriter.Write(rawValueBuilder.ToString());
  213.  
  214. streamWriter.Close();
  215. streamWriter.Dispose();
  216. }
  217. }
  218. }
  219.  
  220. }
  221. }

  2-CSV映射类特性:

  

  1. using System;
  2.  
  3. namespace PaymentAccountAPI.CSV
  4. {
  5. /// <summary>
  6. /// Csv文件类特性标记
  7. /// </summary>
  8. [System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple = false)]
  9. public class CsvColumnAttribute : System.Attribute
  10. {
  11. internal const int defaultTitleIndex = Int32.MaxValue;
  12. /// <summary>
  13. /// 标题
  14. /// </summary>
  15. public string Title { get; set; }
  16. /// <summary>
  17. /// 标题位置(从0开始)
  18. /// </summary>
  19. public int TitleIndex { get; set; }
  20. /// <summary>
  21. /// 字符输出格式(数字和日期类型需要)
  22. /// </summary>
  23. public string OutputFormat { get; set; }
  24.  
  25. public CsvColumnAttribute()
  26. {
  27. Title = "";
  28. TitleIndex = defaultTitleIndex;
  29. OutputFormat = "";
  30. }
  31.  
  32. public CsvColumnAttribute(string title, int titleIndex, string outputFormat)
  33. {
  34. Title = title;
  35. TitleIndex = titleIndex;
  36. OutputFormat = outputFormat;
  37. }
  38. }
  39. }

  3-CSV文件描述信息类:

  

  1. using System.Text;
  2.  
  3. namespace PaymentAccountAPI.CSV
  4. {
  5. public class CsvFileDescription
  6. {
  7. public CsvFileDescription() : this()
  8. {
  9. }
  10. public CsvFileDescription(int titleRawIndex) : this(',', titleRawIndex, Encoding.UTF8)
  11. {
  12. }
  13. public CsvFileDescription(char separatorChar, int titleRawIndex, Encoding encoding)
  14. {
  15. this.SeparatorChar = separatorChar;
  16. this.TitleRawIndex = titleRawIndex;
  17. this.Encoding = encoding;
  18. }
  19.  
  20. /// <summary>
  21. /// CSV文件字符编码
  22. /// </summary>
  23. public Encoding Encoding { get; set; }
  24.  
  25. /// <summary>
  26. /// 分隔符(默认为(,),也可以是其他分隔符如(\t))
  27. /// </summary>
  28. public char SeparatorChar { get; set; }
  29. /// <summary>
  30. /// 标题所在行位置(默认为0,没有标题填-1)
  31. /// </summary>
  32. public int TitleRawIndex { get; set; }
  33.  
  34. }
  35. }

  4-映射类获取关系帮助类:

  

  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Reflection;
  4.  
  5. namespace PaymentAccountAPI.CSV
  6. {
  7. /// <summary>
  8. /// 字段映射类
  9. /// </summary>
  10. public class FieldMapper
  11. {
  12. /// <summary>
  13. /// 属性信息
  14. /// </summary>
  15. public PropertyInfo PropertyInfo { get; set; }
  16. /// <summary>
  17. /// 标题
  18. /// </summary>
  19. public string CSVTitle { get; set; }
  20. /// <summary>
  21. /// 标题下标位置
  22. /// </summary>
  23. public int CSVTitleIndex { get; set; }
  24. /// <summary>
  25. /// 字符输出格式(数字和日期类型需要)
  26. /// </summary>
  27. public string OutputFormat { get; set; }
  28.  
  29. public static List<FieldMapper> GetModelFieldMapper<T>()
  30. {
  31. List<FieldMapper> fieldMapperList = new List<FieldMapper>();
  32.  
  33. List<PropertyInfo> tPropertyInfoList = typeof(T).GetProperties().ToList();
  34. CsvColumnAttribute csvColumnAttribute = null;
  35. foreach (var tPropertyInfo in tPropertyInfoList)
  36. {
  37. csvColumnAttribute = (CsvColumnAttribute)tPropertyInfo.GetCustomAttribute(typeof(CsvColumnAttribute));
  38. if (csvColumnAttribute != null)
  39. {
  40. fieldMapperList.Add(new FieldMapper
  41. {
  42. PropertyInfo = tPropertyInfo,
  43. CSVTitle = csvColumnAttribute.Title,
  44. CSVTitleIndex = csvColumnAttribute.TitleIndex,
  45. OutputFormat = csvColumnAttribute.OutputFormat
  46. });
  47. }
  48. }
  49. return fieldMapperList;
  50. }
  51.  
  52. }
  53.  
  54. }

  5-其他扩展类:

  

  1. namespace PaymentAccountAPI.Helper
  2. {
  3. public class StringHelper
  4. {
  5. /// <summary>
  6. /// 获取字符串中第strPosition个位置的str的下标
  7. /// </summary>
  8. /// <param name="text"></param>
  9. /// <param name="str"></param>
  10. /// <param name="strPosition"></param>
  11. /// <returns></returns>
  12. public static int GetIndexOfStr(string text, string str, int strPosition)
  13. {
  14. int strIndex = -;
  15.  
  16. int currentPosition = ;
  17. if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(str) && strPosition >= )
  18. {
  19. do
  20. {
  21. currentPosition++;
  22. if (strIndex == -)
  23. {
  24. strIndex = text.IndexOf(str);
  25. }
  26. else
  27. {
  28. strIndex = text.IndexOf(str, strIndex + );
  29. }
  30. } while (currentPosition < strPosition);
  31. }
  32.  
  33. return strIndex;
  34. }
  35. }
  36. }

  最后就是将CsvHelper注入到单例中,就可以使用了...

C#_.net core 3.0自定义读取.csv文件数据_解决首行不是标题的问题_Linqtocsv改进的更多相关文章

  1. C#使用Linq to csv读取.csv文件数据

    前言:今日遇到了一个需要读取CSV文件类型的EXCEL文档数据的问题,原本使用NPOI的解决方案直接读取文档数据,最后失败了,主要是文件的类型版本等信息不兼容导致.其他同事有使用linq to csv ...

  2. matlab读取csv文件数据并绘图

    circle.m(画二维圆的函数) %该函数是画二维圆圈,输入圆心坐标和半径%rectangle()函数参数‘linewidth’修饰曲线的宽度%'edgecolor','r',edgecolor表示 ...

  3. python读取csv文件数据绘制图像,例子绘制天气每天最高最低气温气象图

  4. C#使用Linq to csv读取.csv文件数据2_处理含有非列名数据的方法(说明信息等)

    第一篇博客为:https://www.cnblogs.com/lxhbky/p/11884474.html 本文主要是为了解决上面博客遗留的一个含有不规范数据的一种方法,目前暂时没有从包里发现可以从第 ...

  5. VB 读取csv文件数据

    Public adoConn As New ADODB.Connection Private Sub csv() adoConn.ConnectionString = "Driver={Mi ...

  6. php 生成读取csv文件并解决中文乱码

    csv其实是文本文件,但是里面的内容是利用逗号分隔的. 1. 生成csv文件 function new_csv($arr) { $string=""; foreach ($arr ...

  7. NET Core 2.0 自定义

    ASP.NET Core 2.0 自定义 _ViewStart 和 _ViewImports 的目录位置 在 ASP.NET Core 里扩展 Razor 查找视图目录不是什么新鲜和困难的事情,但 _ ...

  8. ASP.NET Core 5.0 中读取Request中Body信息

    ASP.NET Core 5.0 中读取Request中Body信息 记录一下如何读取Request中Body信息 public class ValuesController : Controller ...

  9. VB6.0 读取CSV文件

    最近做了一个Upload文件的需求,文件的格式为CSV,读取文件的方法整理了一下,如下: 1.先写了一个读取CSV文件的Function: '读取CSV文件 '假设传入的参数strFile=C:\Do ...

随机推荐

  1. Mysql梳理-关于索引/引擎与锁

    前言 最近突发新型肺炎,本来只有七天的春节假期也因为各种封锁延长到了正月十五,在家实在闲的蛋疼便重新研究了一下Mysql数据库的相关知识,特此总结梳理一下.本文主要围绕以下几点进行: 1.Mysql的 ...

  2. 创建dynamics CRM client-side (十四) - Web API

    Xrm.WebApi 是我们做前端开发不可不缺少的内容. Xrm.WebApi 分为online和offline online: 可以实现和服务器的CRUD交互 offline: 多用于mobile ...

  3. 爬虫之协程,selenium

    1.什么是代理?代理和爬虫之间的关联是什么? 2.在requests的get和post方法常用的参数有哪些?分别有什么作用?(四个参数) - url headers parmas/data proxi ...

  4. ios---设置UITabBarController的字体颜色和大小

    +(void)load{ NSMutableDictionary *attr3=[NSMutableDictionary dictionary]; attr3[NSForegroundColorAtt ...

  5. Kafka系列1:Kafka概况

    Kafka系列1:Kafka概况 Kafka是当前分布式系统中最流行的消息中间件之一,凭借着其高吞吐量的设计,在日志收集系统和消息系统的应用场景中深得开发者喜爱.本篇就聊聊Kafka相关的一些知识点. ...

  6. springIOC源码接口分析(二):ConfigurableBeanFactory

    一 继承功能 1 SingletonBeanRegistry接口 此接口是针对Spring中的单例Bean设计的.提供了统一访问单例Bean的功能,类中定义了以下方法: 2 HierarchicalB ...

  7. Springboot | @RequestBody 接收到的参数对象属性为空

    背景 今天在调试项目的时候遇到一个坑,用Postman发送一个post请求,在Springboot项目使用@RequestBody接收时参数总是报不存在,但是多次检查postman上的请求格式以及项目 ...

  8. Spring(五)核心容器 - 注册 Bean、BeanDefinitionRegistry 简介

    目录 前言 正文 1.BeanDefinitionRegistry 简介 2.registerBeanDefinition 方法注册 Bean 最后 前言 上篇文章我们对 BeanDefinition ...

  9. HDU 1251 统计难题 (Trie树模板题)

    题目链接:点击打开链接 Problem Description Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单 ...

  10. BZOJ2326 [HNOI2011]数学作业(分块矩阵快速幂)

    题意: 定义函数Concatenate (1 ..N)是将所有正整数 1, 2, …, N 顺序连接起来得到的数,如concatenate(1..5)是12345,求concatenate(1...n ...