zoukankan      html  css  js  c++  java
  • 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(@" "); 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); } } }
  • 相关阅读:
    ubuntu samba 服务器设置
    Unable to find the ncurses libraries
    ubuntu 11.04 tftp 设置
    Ubuntu 11.04 NFS 配置
    Ubuntu server 网络设置
    ubuntu 11.04 tslib1.4 编译
    HGE DirectX9.0C版本修改已经完成,发图祝贺一下。
    HGE继续修改绘图底层
    D3D中的AGP内存、系统内存、显存的理解
    For循环和递归的一些区别。
  • 原文地址:https://www.cnblogs.com/Yellow0-0River/p/7614932.html
Copyright © 2011-2022 走看看