c#實現(xiàn)csv文件讀寫的示例詳解
項目中經(jīng)常遇到csv文件的讀寫需求,其中的難點主要是csv文件的解析。本文會介紹csvhelper、textfieldparser、正則表達式三種解析csv文件的方法,順帶也會介紹一下csv文件的寫方法。
csv文件標(biāo)準(zhǔn)
在介紹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數(shù)據(jù)。第二個文件多看一眼都是精神污染,但項目中無法避免會出現(xiàn)這種文件。
rfc 4180
csv文件沒有官方的標(biāo)準(zhǔn),但一般項目都會遵守rfc 4180標(biāo)準(zhǔn)。這是一個非官方的標(biāo)準(zhǔn),內(nèi)容如下:
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) 分隔。
- 文件中的最后一條記錄可能有也可能沒有結(jié)束換行符。
- 可能有一個可選的標(biāo)題行出現(xiàn)在文件的第一行,格式與普通記錄行相同。此標(biāo)題將包含與文件中的字段對應(yīng)的名稱,并且應(yīng)包含與文件其余部分中的記錄相同數(shù)量的字段(標(biāo)題行的存在或不存在應(yīng)通過此 mime 類型的可選“標(biāo)頭”參數(shù)指示)。
- 在標(biāo)題和每條記錄中,可能有一個或多個字段,以逗號分隔。在整個文件中,每行應(yīng)包含相同數(shù)量的字段??崭癖灰暈樽侄蔚囊徊糠?,不應(yīng)忽略。記錄中的最后一個字段后面不能有逗號。
- 每個字段可以用雙引號括起來,也可以不用雙引號(但是某些程序,例如 microsoft excel,根本不使用雙引號)。如果字段沒有用雙引號括起來,那么雙引號可能不會出現(xiàn)在字段內(nèi)。
- 包含換行符 (crlf)、雙引號和逗號的字段應(yīng)該用雙引號括起來。
- 如果使用雙引號將字段括起來,則出現(xiàn)在字段中的雙引號必須在其前面加上另一個雙引號。
簡化標(biāo)準(zhǔn)
上面的標(biāo)準(zhǔn)可能比較拗口,我們對它進行一些簡化。要注意一下,簡化不是簡單的刪減規(guī)則,而是將類似的類似進行合并便于理解。
后面的代碼也會使用簡化標(biāo)準(zhǔn),簡化標(biāo)準(zhǔn)如下:
- 每條記錄位于單獨的行上,由換行符 (crlf) 分隔。
- 注:此處的行不是普通文本意義上的行,是指符合csv文件格式的一條記錄(后面簡稱為csv行),在文本上可能占據(jù)多行。
- 文件中的最后一條記錄需有結(jié)束換行符,文件的第一行為標(biāo)題行(標(biāo)題行包含字段對應(yīng)的名稱,標(biāo)題數(shù)與記錄的字段數(shù)相同)。
- 注:原標(biāo)準(zhǔn)中可有可無的選項統(tǒng)一規(guī)定為必須有,方便后期的解析,而且沒有標(biāo)題行讓別人怎么看數(shù)據(jù)。
- 在標(biāo)題和每條記錄中,可能有一個或多個字段,以逗號分隔。在整個文件中,每行應(yīng)包含相同數(shù)量的字段??崭癖灰暈樽侄蔚囊徊糠?,不應(yīng)忽略。記錄中的最后一個字段后面不能有逗號。
- 注:此標(biāo)準(zhǔn)未做簡化,雖然也有其它標(biāo)準(zhǔn)使用空格、制表符等做分割的,但不使用逗號分割的文件還叫逗號分隔值文件嗎。
- 每個字段都用雙引號括起來,出現(xiàn)在字段中的雙引號必須在其前面加上另一個雙引號
注:原標(biāo)準(zhǔn)有必須使用雙引號和可選雙引號的情況,那全部使用雙引號肯定不會出錯。*
讀寫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; } } }
生成一些測試數(shù)據(jù),代碼如下:
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"; //測試數(shù)據(jù) var records = new list<test> { test, test }; //寫csv文件 /* *直接把后面的寫csv文件代碼復(fù)制到此處 */ //讀csv文件 /* *直接把后面的讀csv文件代碼復(fù)制到此處 */ console.readline(); }</test>
使用csvhelper
csvhelper是用于讀取和寫入 csv 文件的庫,支持自定義類對象的讀寫。
github上標(biāo)星最高的csv文件讀寫c#庫,使用ms-pl、apache 2.0開源協(xié)議。
使用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>()); }</test></test>
如果你只想要拿來就能用的庫,那文章基本上到這里就結(jié)束了。
使用自定義方法
為了與csvhelper區(qū)分,新建一個csvfile類存放自定義讀寫csv文件的代碼,最后會提供類的完整源碼。csvfile類定義如下:
/// <summary> /// csv文件讀寫工具類 /// </summary> public class csvfile { #region 寫csv文件 //具體代碼... #endregion #region 讀csv文件(使用textfieldparser) //具體代碼... #endregion #region 讀csv文件(使用正則表達式) //具體代碼... #endregion }
基于簡化標(biāo)準(zhǔn)的寫csv文件
根據(jù)簡化標(biāo)準(zhǔn)(具體標(biāo)準(zhǔn)內(nèi)容見前文),寫csv文件代碼如下:
#region 寫csv文件 //字段數(shù)組轉(zhuǎn)為csv記錄行 private static string fieldstoline(ienumerable<string> fields) { if (fields == null) return string.empty; fields = fields.select(field => { if (field == null) field = string.empty; //簡化標(biāo)準(zhǔn),所有字段都加雙引號 field = string.format("\"{0}\"", field.replace("\"", "\"\"")); //不簡化標(biāo)準(zhǔn) //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; } //默認(rèn)的字段轉(zhuǎn)換方法 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文件,默認(rèn)第一行為標(biāo)題 /// </summary> /// <typeparam name="t"></typeparam> /// <param name="list" />數(shù)據(jù)列表 /// <param name="path" />文件路徑 /// <param name="append" />追加記錄 /// <param name="func" />字段轉(zhuǎn)換方法 /// <param name="defaultencoding" /> public static void write<t>(list<t> list, string path,bool append=true, func<t, bool,="" ienumerable
- C#操作JSON(序列化與反序列化)的方法詳解
- C#使用kernel32.dll讀寫INI文件的案例詳解
- C#?讀寫編輯INI文件的操作
- 利用C#實現(xiàn)可以繼承的"枚舉"
- C#實現(xiàn)系統(tǒng)休眠或靜止休眠的方法
- C#?計算DataTime的4種時間差的方法(相差天數(shù)、相差小時、相差分鐘、相差秒)
- C#控制臺程序的開發(fā)與打包為一個exe文件實例詳解
- C#實現(xiàn)CSV文件讀寫的示例詳解
- 基于WPF實現(xiàn)擬物音量控件
- 一文掌握C#JSON(2023最新整理)
- C#之Socket客戶端全過程
- C#SynchronizationContext以及Send和Post使用解讀
- C#之如何實現(xiàn)真正的四舍五入
- C#四舍五入MidpointRounding.AwayFromZero解析
- c#中如何去除字符串左邊的0
- C#字符串如何提取數(shù)值(帶小數(shù)點)
- C#正則表達式之Ismatch()的用法解讀
- Unity游戲開發(fā)中的中介者模式的應(yīng)用與實現(xiàn)
- 利用C#/VB.NET實現(xiàn)PPT轉(zhuǎn)換為HTML
- UnityShader片段著色器使用基礎(chǔ)詳解