在介紹CSV檔案的讀寫方法前,我們需要了解一下CSV檔案的格式。
一個簡單的CSV檔案:
Test1,Test2,Test3,Test4,Test5,Test6
str1,str2,str3,str4,str5,str6
str1,str2,str3,str4,str5,str6
一個不簡單的CSV檔案:
"Test1
"",""","Test2
"",""","Test3
"",""","Test4
"",""","Test5
"",""","Test6
"","""
" 中文,D23 ","3DFD4234""""""1232""1S2","ASD1"",""23,,,,213
23F32","
",,asd
" 中文,D23 ","3DFD4234""""""1232""1S2","ASD1"",""23,,,,213
23F32","
",,asd
你沒看錯,上面兩個都是CSV檔案,都只有3行CSV資料。第二個檔案多看一眼都是精神汙染,但專案中無法避免會出現這種檔案。
CSV檔案沒有官方的標準,但一般專案都會遵守 RFC 4180 標準。這是一個非官方的標準,內容如下:
- Each record is located on a separate line, delimited by a line break (CRLF).
- The last record in the file may or may not have an ending line break.
- There maybe an optional header line appearing as the first line of the file with the same format as normal record lines. This header will contain names corresponding to the fields in the file and should contain the same number of fields as the records in the rest of the file (the presence or absence of the header line should be indicated via the optional "header" parameter of this MIME type).
- Within the header and each record, there may be one or more fields, separated by commas. Each line should contain the same number of fields throughout the file. Spaces are considered part of a field and should not be ignored. The last field in the record must not be followed by a comma.
- Each field may or may not be enclosed in double quotes (however some programs, such as Microsoft Excel, do not use double quotes at all). If fields are not enclosed with double quotes, then double quotes may not appear inside the fields.
- Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes.
- If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote.
翻譯一下:
上面的標準可能比較拗口,我們對它進行一些簡化。要注意一下,簡化不是簡單的刪減規則,而是將類似的類似進行合併便於理解。
後面的程式碼也會使用簡化標準,簡化標準如下:
每條記錄位於單獨的行上,由換行符 (CRLF) 分隔。
注:此處的行不是普通文字意義上的行,是指符合CSV檔案格式的一條記錄(後面簡稱為CSV行),在文字上可能佔據多行。
檔案中的最後一條記錄需有結束換行符,檔案的第一行為標題行(標題行包含欄位對應的名稱,標題數與記錄的欄位數相同)。
注:原標準中可有可無的選項統一規定為必須有,方便後期的解析,而且沒有標題行讓別人怎麼看資料。
在標題和每條記錄中,可能有一個或多個欄位,以逗號分隔。在整個檔案中,每行應包含相同數量的欄位。空格被視為欄位的一部分,不應忽略。記錄中的最後一個欄位後面不能有逗號。
注:此標準未做簡化,雖然也有其它標準使用空格、製表符等做分割的,但不使用逗號分割的檔案還叫逗號分隔值檔案嗎。
每個欄位都用雙引號括起來,出現在欄位中的雙引號必須在其前面加上另一個雙引號
注:原標準有必須使用雙引號和可選雙引號的情況,那全部使用雙引號肯定不會出錯。*
在正式讀寫CSV檔案前,我們需要先定義一個用於測試的Test類。程式碼如下:
class Test
{
public string Test1{get;set;}
public string Test2 { get; set; }
public string Test3 { get; set; }
public string Test4 { get; set; }
public string Test5 { get; set; }
public string Test6 { get; set; }
//Parse方法會在自定義讀寫CSV檔案時用到
public static Test Parse (string[]fields )
{
try
{
Test ret = new Test();
ret.Test1 = fields[0];
ret.Test2 = fields[1];
ret.Test3 = fields[2];
ret.Test4 = fields[3];
ret.Test5 = fields[4];
ret.Test6 = fields[5];
return ret;
}
catch (Exception)
{
//做一些例外處理,寫紀錄檔之類的
return null;
}
}
}
生成一些測試資料,程式碼如下:
static void Main(string[] args)
{
//檔案儲存路徑
string path = "tset.csv";
//清理之前的測試檔案
File.Delete("tset.csv");
Test test = new Test();
test.Test1 = " 中文,D23 ";
test.Test2 = "3DFD4234\"\"\"1232\"1S2";
test.Test3 = "ASD1\",\"23,,,,213\r23F32";
test.Test4 = "\r";
test.Test5 = string.Empty;
test.Test6 = "asd";
//測試資料
var records = new List<Test> { test, test };
//寫CSV檔案
/*
*直接把後面的寫CSV檔案程式碼複製到此處
*/
//讀CSV檔案
/*
*直接把後面的讀CSV檔案程式碼複製到此處
*/
Console.ReadLine();
}
CsvHelper 是用於讀取和寫入 CSV 檔案的庫,支援自定義類物件的讀寫。
github上標星最高的CSV檔案讀寫C#庫,使用MS-PL、Apache 2.0開源協定。
使用NuGet下載CsvHelper,讀寫CSV檔案的程式碼如下:
//寫CSV檔案
using (var writer = new StreamWriter(path))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteRecords(records);
}
using (var writer = new StreamWriter(path,true))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
//追加
foreach (var record in records)
{
csv.WriteRecord(record);
}
}
//讀CSV檔案
using (var reader = new StreamReader(path))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
records = csv.GetRecords<Test>().ToList();
//逐行讀取
//records.Add(csv.GetRecord<Test>());
}
如果你只想要拿來就能用的庫,那文章基本上到這裡就結束了。
為了與CsvHelper區分,新建一個CsvFile類存放自定義讀寫CSV檔案的程式碼,最後會提供類的完整原始碼。CsvFile類定義如下:
/// <summary>
/// CSV檔案讀寫工具類
/// </summary>
public class CsvFile
{
#region 寫CSV檔案
//具體程式碼...
#endregion
#region 讀CSV檔案(使用TextFieldParser)
//具體程式碼...
#endregion
#region 讀CSV檔案(使用正規表示式)
//具體程式碼...
#endregion
}
根據簡化標準(具體標準內容見前文),寫CSV檔案程式碼如下:
#region 寫CSV檔案
//欄位陣列轉為CSV記錄行
private static string FieldsToLine(IEnumerable<string> fields)
{
if (fields == null) return string.Empty;
fields = fields.Select(field =>
{
if (field == null) field = string.Empty;
//簡化標準,所有欄位都加雙引號
field = string.Format("\"{0}\"", field.Replace("\"", "\"\""));
//不簡化標準
//field = field.Replace("\"", "\"\"");
//if (field.IndexOfAny(new char[] { ',', '"', ' ', '\r' }) != -1)
//{
// field = string.Format("\"{0}\"", field);
//}
return field;
});
string line = string.Format("{0}{1}", string.Join(",", fields), Environment.NewLine);
return line;
}
//預設的欄位轉換方法
private static IEnumerable<string> GetObjFields<T>(T obj, bool isTitle) where T : class
{
IEnumerable<string> fields;
if (isTitle)
{
fields = obj.GetType().GetProperties().Select(pro => pro.Name);
}
else
{
fields = obj.GetType().GetProperties().Select(pro => pro.GetValue(obj)?.ToString());
}
return fields;
}
/// <summary>
/// 寫CSV檔案,預設第一行為標題
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">資料列表</param>
/// <param name="path">檔案路徑</param>
/// <param name="append">追加記錄</param>
/// <param name="func">欄位轉換方法</param>
/// <param name="defaultEncoding"></param>
public static void Write<T>(List<T> list, string path,bool append=true, Func<T, bool, IEnumerable<string>> func = null, Encoding defaultEncoding = null) where T : class
{
if (list == null || list.Count == 0) return;
if (defaultEncoding == null)
{
defaultEncoding = Encoding.UTF8;
}
if (func == null)
{
func = GetObjFields;
}
if (!File.Exists(path)|| !append)
{
var fields = func(list[0], true);
string title = FieldsToLine(fields);
File.WriteAllText(path, title, defaultEncoding);
}
using (StreamWriter sw = new StreamWriter(path, true, defaultEncoding))
{
list.ForEach(obj =>
{
var fields = func(obj, false);
string line = FieldsToLine(fields);
sw.Write(line);
});
}
}
#endregion
使用時,程式碼如下:
//寫CSV檔案
//使用自定義的欄位轉換方法,也是文章開頭複雜CSV檔案使用欄位轉換方法
CsvFile.Write(records, path, true, new Func<Test, bool, IEnumerable<string>>((obj, isTitle) =>
{
IEnumerable<string> fields;
if (isTitle)
{
fields = obj.GetType().GetProperties().Select(pro => pro.Name + Environment.NewLine + "\",\"");
}
else
{
fields = obj.GetType().GetProperties().Select(pro => pro.GetValue(obj)?.ToString());
}
return fields;
}));
//使用預設的欄位轉換方法
//CsvFile.Write(records, path);
你也可以使用預設的欄位轉換方法,程式碼如下:
CsvFile.Save(records, path);
TextFieldParser是VB中解析CSV檔案的類,C#雖然沒有類似功能的類,不過可以呼叫VB的TextFieldParser來實現功能。
TextFieldParser解析CSV檔案的程式碼如下:
#region 讀CSV檔案(使用TextFieldParser)
/// <summary>
/// 讀CSV檔案,預設第一行為標題
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path">檔案路徑</param>
/// <param name="func">欄位解析規則</param>
/// <param name="defaultEncoding">檔案編碼</param>
/// <returns></returns>
public static List<T> Read<T>(string path, Func<string[], T> func, Encoding defaultEncoding = null) where T : class
{
if (defaultEncoding == null)
{
defaultEncoding = Encoding.UTF8;
}
List<T> list = new List<T>();
using (TextFieldParser parser = new TextFieldParser(path, defaultEncoding))
{
parser.TextFieldType = FieldType.Delimited;
//設定逗號分隔符
parser.SetDelimiters(",");
//設定不忽略欄位前後的空格
parser.TrimWhiteSpace = false;
bool isLine = false;
while (!parser.EndOfData)
{
string[] fields = parser.ReadFields();
if (isLine)
{
var obj = func(fields);
if (obj != null) list.Add(obj);
}
else
{
//忽略標題行業
isLine = true;
}
}
}
return list;
}
#endregion
使用時,程式碼如下:
//讀CSV檔案
records = CsvFile.Read(path, Test.Parse);
如果你有一個問題,想用正規表示式來解決,那麼你就有兩個問題了。
正規表示式有一定的學習門檻,而且學習後不經常使用就會忘記。正規表示式解決的大多數是一些不易變更需求的問題,這就導致一個穩定可用的正規表示式可以傳好幾代。
本節的正規表示式來自 《精通正規表示式(第3版)》 第6章 打造高效正規表示式——簡單的消除迴圈的例子,有興趣的可以去了解一下,表示式說明如下:
注:這本書最終版的解析CSV檔案的正規表示式是Jave版的使用佔有優先量詞取代固化分組的版本,也是百度上經常見到的版本。不過佔有優先量詞在C#中有點問題,本人能力有限解決不了,所以使用了上圖的版本。不過,這兩版正規表示式效能上沒有差異。
正規表示式解析CSV檔案程式碼如下:
#region 讀CSV檔案(使用正規表示式)
/// <summary>
/// 讀CSV檔案,預設第一行為標題
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path">檔案路徑</param>
/// <param name="func">欄位解析規則</param>
/// <param name="defaultEncoding">檔案編碼</param>
/// <returns></returns>
public static List<T> Read_Regex<T>(string path, Func<string[], T> func, Encoding defaultEncoding = null) where T : class
{
List<T> list = new List<T>();
StringBuilder sbr = new StringBuilder(100);
Regex lineReg = new Regex("\"");
Regex fieldReg = new Regex("\\G(?:^|,)(?:\"((?>[^\"]*)(?>\"\"[^\"]*)*)\"|([^\",]*))");
Regex quotesReg = new Regex("\"\"");
bool isLine = false;
string line = string.Empty;
using (StreamReader sr = new StreamReader(path))
{
while (null != (line = ReadLine(sr)))
{
sbr.Append(line);
string str = sbr.ToString();
//一個完整的CSV記錄行,它的雙引號一定是偶數
if (lineReg.Matches(sbr.ToString()).Count % 2 == 0)
{
if (isLine)
{
var fields = ParseCsvLine(sbr.ToString(), fieldReg, quotesReg).ToArray();
var obj = func(fields.ToArray());
if (obj != null) list.Add(obj);
}
else
{
//忽略標題行業
isLine = true;
}
sbr.Clear();
}
else
{
sbr.Append(Environment.NewLine);
}
}
}
if (sbr.Length > 0)
{
//有解析失敗的字串,報錯或忽略
}
return list;
}
//重寫ReadLine方法,只有\r\n才是正確的一行
private static string ReadLine(StreamReader sr)
{
StringBuilder sbr = new StringBuilder();
char c;
int cInt;
while (-1 != (cInt =sr.Read()))
{
c = (char)cInt;
if (c == '\n' && sbr.Length > 0 && sbr[sbr.Length - 1] == '\r')
{
sbr.Remove(sbr.Length - 1, 1);
return sbr.ToString();
}
else
{
sbr.Append(c);
}
}
return sbr.Length>0?sbr.ToString():null;
}
private static List<string> ParseCsvLine(string line, Regex fieldReg, Regex quotesReg)
{
var fieldMath = fieldReg.Match(line);
List<string> fields = new List<string>();
while (fieldMath.Success)
{
string field;
if (fieldMath.Groups[1].Success)
{
field = quotesReg.Replace(fieldMath.Groups[1].Value, "\"");
}
else
{
field = fieldMath.Groups[2].Value;
}
fields.Add(field);
fieldMath = fieldMath.NextMatch();
}
return fields;
}
#endregion
使用時程式碼如下:
//讀CSV檔案
records = CsvFile.Read_Regex(path, Test.Parse);
目前還未發現正規表示式解析有什麼bug,不過還是不建議使用。
完整的CsvFile類程式碼如下:
using Microsoft.VisualBasic.FileIO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApp4
{
/// <summary>
/// CSV檔案讀寫工具類
/// </summary>
public class CsvFile
{
#region 寫CSV檔案
//欄位陣列轉為CSV記錄行
private static string FieldsToLine(IEnumerable<string> fields)
{
if (fields == null) return string.Empty;
fields = fields.Select(field =>
{
if (field == null) field = string.Empty;
//所有欄位都加雙引號
field = string.Format("\"{0}\"", field.Replace("\"", "\"\""));
//不簡化
//field = field.Replace("\"", "\"\"");
//if (field.IndexOfAny(new char[] { ',', '"', ' ', '\r' }) != -1)
//{
// field = string.Format("\"{0}\"", field);
//}
return field;
});
string line = string.Format("{0}{1}", string.Join(",", fields), Environment.NewLine);
return line;
}
//預設的欄位轉換方法
private static IEnumerable<string> GetObjFields<T>(T obj, bool isTitle) where T : class
{
IEnumerable<string> fields;
if (isTitle)
{
fields = obj.GetType().GetProperties().Select(pro => pro.Name);
}
else
{
fields = obj.GetType().GetProperties().Select(pro => pro.GetValue(obj)?.ToString());
}
return fields;
}
/// <summary>
/// 寫CSV檔案,預設第一行為標題
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">資料列表</param>
/// <param name="path">檔案路徑</param>
/// <param name="append">追加記錄</param>
/// <param name="func">欄位轉換方法</param>
/// <param name="defaultEncoding"></param>
public static void Write<T>(List<T> list, string path,bool append=true, Func<T, bool, IEnumerable<string>> func = null, Encoding defaultEncoding = null) where T : class
{
if (list == null || list.Count == 0) return;
if (defaultEncoding == null)
{
defaultEncoding = Encoding.UTF8;
}
if (func == null)
{
func = GetObjFields;
}
if (!File.Exists(path)|| !append)
{
var fields = func(list[0], true);
string title = FieldsToLine(fields);
File.WriteAllText(path, title, defaultEncoding);
}
using (StreamWriter sw = new StreamWriter(path, true, defaultEncoding))
{
list.ForEach(obj =>
{
var fields = func(obj, false);
string line = FieldsToLine(fields);
sw.Write(line);
});
}
}
#endregion
#region 讀CSV檔案(使用TextFieldParser)
/// <summary>
/// 讀CSV檔案,預設第一行為標題
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path">檔案路徑</param>
/// <param name="func">欄位解析規則</param>
/// <param name="defaultEncoding">檔案編碼</param>
/// <returns></returns>
public static List<T> Read<T>(string path, Func<string[], T> func, Encoding defaultEncoding = null) where T : class
{
if (defaultEncoding == null)
{
defaultEncoding = Encoding.UTF8;
}
List<T> list = new List<T>();
using (TextFieldParser parser = new TextFieldParser(path, defaultEncoding))
{
parser.TextFieldType = FieldType.Delimited;
//設定逗號分隔符
parser.SetDelimiters(",");
//設定不忽略欄位前後的空格
parser.TrimWhiteSpace = false;
bool isLine = false;
while (!parser.EndOfData)
{
string[] fields = parser.ReadFields();
if (isLine)
{
var obj = func(fields);
if (obj != null) list.Add(obj);
}
else
{
//忽略標題行業
isLine = true;
}
}
}
return list;
}
#endregion
#region 讀CSV檔案(使用正規表示式)
/// <summary>
/// 讀CSV檔案,預設第一行為標題
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path">檔案路徑</param>
/// <param name="func">欄位解析規則</param>
/// <param name="defaultEncoding">檔案編碼</param>
/// <returns></returns>
public static List<T> Read_Regex<T>(string path, Func<string[], T> func, Encoding defaultEncoding = null) where T : class
{
List<T> list = new List<T>();
StringBuilder sbr = new StringBuilder(100);
Regex lineReg = new Regex("\"");
Regex fieldReg = new Regex("\\G(?:^|,)(?:\"((?>[^\"]*)(?>\"\"[^\"]*)*)\"|([^\",]*))");
Regex quotesReg = new Regex("\"\"");
bool isLine = false;
string line = string.Empty;
using (StreamReader sr = new StreamReader(path))
{
while (null != (line = ReadLine(sr)))
{
sbr.Append(line);
string str = sbr.ToString();
//一個完整的CSV記錄行,它的雙引號一定是偶數
if (lineReg.Matches(sbr.ToString()).Count % 2 == 0)
{
if (isLine)
{
var fields = ParseCsvLine(sbr.ToString(), fieldReg, quotesReg).ToArray();
var obj = func(fields.ToArray());
if (obj != null) list.Add(obj);
}
else
{
//忽略標題行業
isLine = true;
}
sbr.Clear();
}
else
{
sbr.Append(Environment.NewLine);
}
}
}
if (sbr.Length > 0)
{
//有解析失敗的字串,報錯或忽略
}
return list;
}
//重寫ReadLine方法,只有\r\n才是正確的一行
private static string ReadLine(StreamReader sr)
{
StringBuilder sbr = new StringBuilder();
char c;
int cInt;
while (-1 != (cInt =sr.Read()))
{
c = (char)cInt;
if (c == '\n' && sbr.Length > 0 && sbr[sbr.Length - 1] == '\r')
{
sbr.Remove(sbr.Length - 1, 1);
return sbr.ToString();
}
else
{
sbr.Append(c);
}
}
return sbr.Length>0?sbr.ToString():null;
}
private static List<string> ParseCsvLine(string line, Regex fieldReg, Regex quotesReg)
{
var fieldMath = fieldReg.Match(line);
List<string> fields = new List<string>();
while (fieldMath.Success)
{
string field;
if (fieldMath.Groups[1].Success)
{
field = quotesReg.Replace(fieldMath.Groups[1].Value, "\"");
}
else
{
field = fieldMath.Groups[2].Value;
}
fields.Add(field);
fieldMath = fieldMath.NextMatch();
}
return fields;
}
#endregion
}
}
使用方法如下:
//寫CSV檔案
CsvFile.Write(records, path, true, new Func<Test, bool, IEnumerable<string>>((obj, isTitle) =>
{
IEnumerable<string> fields;
if (isTitle)
{
fields = obj.GetType().GetProperties().Select(pro => pro.Name + Environment.NewLine + "\",\"");
}
else
{
fields = obj.GetType().GetProperties().Select(pro => pro.GetValue(obj)?.ToString());
}
return fields;
}));
//讀CSV檔案
records = CsvFile.Read(path, Test.Parse);
//讀CSV檔案
records = CsvFile.Read_Regex(path, Test.Parse);