C#解析csv文件

Csv文件规则:

  1. 开头不留空,以行为单位;
  2. 可含或不含列名,含列名则居文件第一行;
  3. 一行数据不跨行,无空行;
  4. 以半角逗号(即,)作分隔符,列为空也要表达其存在;
  5. 列内容如存在半角逗号(即,),则用半角双引号("")将该字段值包含起来;
  6. 列内容如存在半角双引号(即"),则用两个双引号("")将其替换,再用半角双引号引号(即"")将该字段值包含起来;
  7. 文件读写时引号,逗号操作规则互逆;
  8. 内码格式不限,可为 ASCII、Unicode 或者其他;
  9. 不支持特殊字符。

csv文件的生成,最简单的即为:Excel->文件->另存为(.csv) 

 

根据规则可知,csv的每一行数据的引号个数必定为偶数个,每行中的每项数据个数必定为偶数个,即不可能存在双引号个数为奇数个的数据项,故可据此编写解析csv代码:

 

using System;
using System.Collections;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class CsvHelper
{
    /// <summary>
    /// 字符串是否包含奇数个引号
    /// </summary>
    /// <param name="str">相关字符串</param>
    /// <returns></returns>
    private static bool _isOddDoubleQuota(string str)
    {
        return _getDoubleQuotaCount(str) % 2 == 1;
    }

    private static int _getDoubleQuotaCount(string str)
    {
        string[] strArray = str.Split('"');
        int doubleQuotaCount = strArray.Length - 1;
        doubleQuotaCount = doubleQuotaCount < 0 ? 0 : doubleQuotaCount;
        return doubleQuotaCount;
    }

    /**
     * csv的每一行的每一项的引号个数必定为偶数
   * 生成的Dictionary<string,List<string>>以每一列的第一行元素作为key,其它元素的集合作为value
*/ public static Dictionary<string, List<string>> AnalysisCsvByStr(string csvInfo) { //首行的每列数据项作为字典的Key Dictionary<string, List<string>> csvInfoDic = new Dictionary<string, List<string>>(); Regex regex = new Regex(@"\r\n"); string[] infoLines = regex.Split(csvInfo); List<string>[] itemListArray = new List<string>[0]; for (int i = 0, length = infoLines.Length; i < length; i++) { if (string.IsNullOrEmpty(infoLines[i])) { continue; } string[] lineInfoArray = infoLines[i].Split(','); List<string> rowItemList = new List<string>(); string strTemp = string.Empty; for (int j = 0; j < lineInfoArray.Length; j++) { strTemp += lineInfoArray[j]; if (_isOddDoubleQuota(strTemp)) { if (j != lineInfoArray.Length - 1) { strTemp += ","; } } else { if (strTemp.StartsWith("\"") && strTemp.EndsWith("\"")) { strTemp = strTemp.Substring(1, strTemp.Length - 2); } rowItemList.Add(strTemp); strTemp = string.Empty; } } if (i == 0) { itemListArray = new List<string>[rowItemList.Count]; for (int temp = 0; temp < itemListArray.Length; temp++) { itemListArray[temp] = new List<string>(); } } int indexTemp = 0; for (; indexTemp < rowItemList.Count; indexTemp++) { if (indexTemp == itemListArray.Length) { throw new ArgumentException("csv文件有误"); } itemListArray[indexTemp].Add(rowItemList[indexTemp]); } if (indexTemp < itemListArray.Length - 1) { throw new ArgumentException("csv文件有误"); } } for (int i = 0; i < itemListArray.Length; i++) { string key = itemListArray[i][0];
       //去除第一个元素,其它元素集合作为value itemListArray[i].RemoveAt(
0); csvInfoDic.Add(key, itemListArray[i]); } return csvInfoDic; } public static Dictionary<string, List<string>> AnalysisCsvByFile(string csvPath) { if (File.Exists(csvPath)) { string csvInfo = File.ReadAllText(csvPath, Encoding.UTF8); return AnalysisCsvByStr(csvInfo); } else { throw new FileNotFoundException("未找到文件:" + csvPath); } } }

 

转载于:https://www.cnblogs.com/Yellow0-0River/p/7614932.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值