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); } } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM