C#如何实现读写CSV文件(csv,开发技术)

时间:2024-04-30 06:47:26 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

CSV文件标准

在介绍CSV文件的读写方法前,我们需要了解一下CSV文件的格式。

文件示例

一个简单的CSV文件:

Test1,Test2,Test3,Test4,Test5,Test6str1,str2,str3,str4,str5,str6str1,str2,str3,str4,str5,str6

一个不简单的CSV文件:

"Test1"",""","Test2"",""","Test3"",""","Test4"",""","Test5"",""","Test6"",""""中文,D23","3DFD4234""""""1232""1S2","ASD1"",""23,,,,21323F32","",,asd"中文,D23","3DFD4234""""""1232""1S2","ASD1"",""23,,,,21323F32","",,asd

你没看错,上面两个都是CSV文件,都只有3行CSV数据。第二个文件多看一眼都是精神污染,但项目中无法避免会出现这种文件。

RFC 4180

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) 分隔。

  • 文件中的最后一条记录可能有也可能没有结束换行符。

  • 可能有一个可选的标题行出现在文件的第一行,格式与普通记录行相同。此标题将包含与文件中的字段对应的名称,并且应包含与文件其余部分中的记录相同数量的字段(标题行的存在或不存在应通过此 MIME 类型的可选“标头”参数指示)。

  • 在标题和每条记录中,可能有一个或多个字段,以逗号分隔。在整个文件中,每行应包含相同数量的字段。空格被视为字段的一部分,不应忽略。记录中的最后一个字段后面不能有逗号。

  • 每个字段可以用双引号括起来,也可以不用双引号(但是某些程序,例如 Microsoft Excel,根本不使用双引号)。如果字段没有用双引号括起来,那么双引号可能不会出现在字段内。

  • 包含换行符 (CRLF)、双引号和逗号的字段应该用双引号括起来。

  • 如果使用双引号将字段括起来,则出现在字段中的双引号必须在其前面加上另一个双引号。

简化标准

上面的标准可能比较拗口,我们对它进行一些简化。要注意一下,简化不是简单的删减规则,而是将类似的类似进行合并便于理解。
后面的代码也会使用简化标准,简化标准如下:

  • 每条记录位于单独的行上,由换行符 (CRLF) 分隔。

  • 注:此处的行不是普通文本意义上的行,是指符合CSV文件格式的一条记录(后面简称为CSV行),在文本上可能占据多行。

  • 文件中的最后一条记录需有结束换行符,文件的第一行为标题行(标题行包含字段对应的名称,标题数与记录的字段数相同)。

  • 注:原标准中可有可无的选项统一规定为必须有,方便后期的解析,而且没有标题行让别人怎么看数据。

  • 在标题和每条记录中,可能有一个或多个字段,以逗号分隔。在整个文件中,每行应包含相同数量的字段空格被视为字段的一部分,不应忽略。记录中的最后一个字段后面不能有逗号

  • 注:此标准未做简化,虽然也有其它标准使用空格、制表符等做分割的,但不使用逗号分割的文件还叫逗号分隔值文件吗。

  • 每个字段都用双引号括起来,出现在字段中的双引号必须在其前面加上另一个双引号

  • 注:原标准有必须使用双引号和可选双引号的情况,那全部使用双引号肯定不会出错。*

读写CSV文件

在正式读写CSV文件前,我们需要先定义一个用于测试的Test类。代码如下:

classTest{publicstringTest1{get;set;}publicstringTest2{get;set;}publicstringTest3{get;set;}publicstringTest4{get;set;}publicstringTest5{get;set;}publicstringTest6{get;set;}//Parse方法会在自定义读写CSV文件时用到publicstaticTestParse(string[]fields){try{Testret=newTest();ret.Test1=fields[0];ret.Test2=fields[1];ret.Test3=fields[2];ret.Test4=fields[3];ret.Test5=fields[4];ret.Test6=fields[5];returnret;}catch(Exception){//做一些异常处理,写日志之类的returnnull;}}}

生成一些测试数据,代码如下:

staticvoidMain(string[]args){//文件保存路径stringpath="tset.csv";//清理之前的测试文件File.Delete("tset.csv");Testtest=newTest();test.Test1="中文,D23";test.Test2="3DFD4234\"\"\"1232\"1S2";test.Test3="ASD1\",\"23,,,,213\r23F32";test.Test4="\r";test.Test5=string.Empty;test.Test6="asd";//测试数据varrecords=newList<Test>{test,test};//写CSV文件/**直接把后面的写CSV文件代码复制到此处*///读CSV文件/**直接把后面的读CSV文件代码复制到此处*/Console.ReadLine();}

使用CsvHelper

CsvHelper是用于读取和写入 CSV 文件的库,支持自定义类对象的读写。

github上标星最高的CSV文件读写C#库,使用MS-PL、Apache 2.0开源协议。

使用NuGet下载CsvHelper,读写CSV文件的代码如下:

//写CSV文件using(varwriter=newStreamWriter(path))using(varcsv=newCsvWriter(writer,CultureInfo.InvariantCulture)){csv.WriteRecords(records);}using(varwriter=newStreamWriter(path,true))using(varcsv=newCsvWriter(writer,CultureInfo.InvariantCulture)){//追加foreach(varrecordinrecords){csv.WriteRecord(record);}}//读CSV文件using(varreader=newStreamReader(path))using(varcsv=newCsvReader(reader,CultureInfo.InvariantCulture)){records=csv.GetRecords<Test>().ToList();//逐行读取//records.Add(csv.GetRecord<Test>());}

如果你只想要拿来就能用的库,那文章基本上到这里就结束了。

使用自定义方法

为了与CsvHelper区分,新建一个CsvFile类存放自定义读写CSV文件的代码,最后会提供类的完整源码。CsvFile类定义如下:

///<summary>///CSV文件读写工具类///</summary>publicclassCsvFile{#region写CSV文件//具体代码...#endregion#region读CSV文件(使用TextFieldParser)//具体代码...#endregion#region读CSV文件(使用正则表达式)//具体代码...#endregion}

基于简化标准的写CSV文件

根据简化标准(具体标准内容见前文),写CSV文件代码如下:

#region写CSV文件//字段数组转为CSV记录行privatestaticstringFieldsToLine(IEnumerable<string>fields){if(fields==null)returnstring.Empty;fields=fields.Select(field=>{if(field==null)field=string.Empty;//简化标准,所有字段都加双引号field=string.Format("\"{0}\"",field.Replace("\"","\"\""));//不简化标准//field=field.Replace("\"","\"\"");//if(field.IndexOfAny(newchar[]{',','"','','\r'})!=-1)//{//field=string.Format("\"{0}\"",field);//}returnfield;});stringline=string.Format("{0}{1}",string.Join(",",fields),Environment.NewLine);returnline;}//默认的字段转换方法privatestaticIEnumerable<string>GetObjFields<T>(Tobj,boolisTitle)whereT: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());}returnfields;}///<summary>///写CSV文件,默认第一行为标题///</summary>///<typeparamname="T"></typeparam>///<paramname="list">数据列表</param>///<paramname="path">文件路径</param>///<paramname="append">追加记录</param>///<paramname="func">字段转换方法</param>///<paramname="defaultEncoding"></param>publicstaticvoidWrite<T>(List<T>list,stringpath,boolappend=true,Func<T,bool,IEnumerable<string>>func=null,EncodingdefaultEncoding=null)whereT:class{if(list==null||list.Count==0)return;if(defaultEncoding==null){defaultEncoding=Encoding.UTF8;}if(func==null){func=GetObjFields;}if(!File.Exists(path)||!append){varfields=func(list[0],true);stringtitle=FieldsToLine(fields);File.WriteAllText(path,title,defaultEncoding);}using(StreamWritersw=newStreamWriter(path,true,defaultEncoding)){list.ForEach(obj=>{varfields=func(obj,false);stringline=FieldsToLine(fields);sw.Write(line);});}}#endregion

使用时,代码如下:

//写CSV文件//使用自定义的字段转换方法,也是文章开头复杂CSV文件使用字段转换方法CsvFile.Write(records,path,true,newFunc<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());}returnfields;}));//使用默认的字段转换方法//CsvFile.Write(records,path);

你也可以使用默认的字段转换方法,代码如下:

CsvFile.Save(records,path);

使用TextFieldParser解析CSV文件

TextFieldParser是VB中解析CSV文件的类,C#虽然没有类似功能的类,不过可以调用VB的TextFieldParser来实现功能。

TextFieldParser解析CSV文件的代码如下:

#region读CSV文件(使用TextFieldParser)///<summary>///读CSV文件,默认第一行为标题///</summary>///<typeparamname="T"></typeparam>///<paramname="path">文件路径</param>///<paramname="func">字段解析规则</param>///<paramname="defaultEncoding">文件编码</param>///<returns></returns>publicstaticList<T>Read<T>(stringpath,Func<string[],T>func,EncodingdefaultEncoding=null)whereT:class{if(defaultEncoding==null){defaultEncoding=Encoding.UTF8;}List<T>list=newList<T>();using(TextFieldParserparser=newTextFieldParser(path,defaultEncoding)){parser.TextFieldType=FieldType.Delimited;//设定逗号分隔符parser.SetDelimiters(",");//设定不忽略字段前后的空格parser.TrimWhiteSpace=false;boolisLine=false;while(!parser.EndOfData){string[]fields=parser.ReadFields();if(isLine){varobj=func(fields);if(obj!=null)list.Add(obj);}else{//忽略标题行业isLine=true;}}}returnlist;}#endregion

使用时,代码如下:

//读CSV文件records=CsvFile.Read(path,Test.Parse);

使用正则表达式解析CSV文件

如果你有一个问题,想用正则表达式来解决,那么你就有两个问题了。

正则表达式有一定的学习门槛,而且学习后不经常使用就会忘记。正则表达式解决的大多数是一些不易变更需求的问题,这就导致一个稳定可用的正则表达式可以传好几代。

本节的正则表达式来自《精通正则表达式(第3版)》 第6章 打造高效正则表达式&mdash;&mdash;简单的消除循环的例子,有兴趣的可以去了解一下,表达式说明如下:

C#如何实现读写CSV文件

注:这本书最终版的解析CSV文件的正则表达式是Jave版的使用占有优先量词取代固化分组的版本,也是百度上经常见到的版本。不过占有优先量词在C#中有点问题,本人能力有限解决不了,所以使用了上图的版本。不过,这两版正则表达式性能上没有差异。

正则表达式解析CSV文件代码如下:

#region读CSV文件(使用正则表达式)///<summary>///读CSV文件,默认第一行为标题///</summary>///<typeparamname="T"></typeparam>///<paramname="path">文件路径</param>///<paramname="func">字段解析规则</param>///<paramname="defaultEncoding">文件编码</param>///<returns></returns>publicstaticList<T>Read_Regex<T>(stringpath,Func<string[],T>func,EncodingdefaultEncoding=null)whereT:class{List<T>list=newList<T>();StringBuildersbr=newStringBuilder(100);RegexlineReg=newRegex("\"");RegexfieldReg=newRegex("\\G(?:^|,)(?:\"((?>[^\"]*)(?>\"\"[^\"]*)*)\"|([^\",]*))");RegexquotesReg=newRegex("\"\"");boolisLine=false;stringline=string.Empty;using(StreamReadersr=newStreamReader(path)){while(null!=(line=ReadLine(sr))){sbr.Append(line);stringstr=sbr.ToString();//一个完整的CSV记录行,它的双引号一定是偶数if(lineReg.Matches(sbr.ToString()).Count%2==0){if(isLine){varfields=ParseCsvLine(sbr.ToString(),fieldReg,quotesReg).ToArray();varobj=func(fields.ToArray());if(obj!=null)list.Add(obj);}else{//忽略标题行业isLine=true;}sbr.Clear();}else{sbr.Append(Environment.NewLine);}}}if(sbr.Length>0){//有解析失败的字符串,报错或忽略}returnlist;}//重写ReadLine方法,只有\r\n才是正确的一行privatestaticstringReadLine(StreamReadersr){StringBuildersbr=newStringBuilder();charc;intcInt;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);returnsbr.ToString();}else{sbr.Append(c);}}returnsbr.Length>0?sbr.ToString():null;}privatestaticList<string>ParseCsvLine(stringline,RegexfieldReg,RegexquotesReg){varfieldMath=fieldReg.Match(line);List<string>fields=newList<string>();while(fieldMath.Success){stringfield;if(fieldMath.Groups[1].Success){field=quotesReg.Replace(fieldMath.Groups[1].Value,"\"");}else{field=fieldMath.Groups[2].Value;}fields.Add(field);fieldMath=fieldMath.NextMatch();}returnfields;}#endregion

使用时代码如下:

//读CSV文件records=CsvFile.Read_Regex(path,Test.Parse);

目前还未发现正则表达式解析有什么bug,不过还是不建议使用。

完整的CsvFile工具类

完整的CsvFile类代码如下:

usingMicrosoft.VisualBasic.FileIO;usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Text;usingSystem.Text.RegularExpressions;namespaceConsoleApp4{///<summary>///CSV文件读写工具类///</summary>publicclassCsvFile{#region写CSV文件//字段数组转为CSV记录行privatestaticstringFieldsToLine(IEnumerable<string>fields){if(fields==null)returnstring.Empty;fields=fields.Select(field=>{if(field==null)field=string.Empty;//所有字段都加双引号field=string.Format("\"{0}\"",field.Replace("\"","\"\""));//不简化//field=field.Replace("\"","\"\"");//if(field.IndexOfAny(newchar[]{',','"','','\r'})!=-1)//{//field=string.Format("\"{0}\"",field);//}returnfield;});stringline=string.Format("{0}{1}",string.Join(",",fields),Environment.NewLine);returnline;}//默认的字段转换方法privatestaticIEnumerable<string>GetObjFields<T>(Tobj,boolisTitle)whereT: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());}returnfields;}///<summary>///写CSV文件,默认第一行为标题///</summary>///<typeparamname="T"></typeparam>///<paramname="list">数据列表</param>///<paramname="path">文件路径</param>///<paramname="append">追加记录</param>///<paramname="func">字段转换方法</param>///<paramname="defaultEncoding"></param>publicstaticvoidWrite<T>(List<T>list,stringpath,boolappend=true,Func<T,bool,IEnumerable<string>>func=null,EncodingdefaultEncoding=null)whereT:class{if(list==null||list.Count==0)return;if(defaultEncoding==null){defaultEncoding=Encoding.UTF8;}if(func==null){func=GetObjFields;}if(!File.Exists(path)||!append){varfields=func(list[0],true);stringtitle=FieldsToLine(fields);File.WriteAllText(path,title,defaultEncoding);}using(StreamWritersw=newStreamWriter(path,true,defaultEncoding)){list.ForEach(obj=>{varfields=func(obj,false);stringline=FieldsToLine(fields);sw.Write(line);});}}#endregion#region读CSV文件(使用TextFieldParser)///<summary>///读CSV文件,默认第一行为标题///</summary>///<typeparamname="T"></typeparam>///<paramname="path">文件路径</param>///<paramname="func">字段解析规则</param>///<paramname="defaultEncoding">文件编码</param>///<returns></returns>publicstaticList<T>Read<T>(stringpath,Func<string[],T>func,EncodingdefaultEncoding=null)whereT:class{if(defaultEncoding==null){defaultEncoding=Encoding.UTF8;}List<T>list=newList<T>();using(TextFieldParserparser=newTextFieldParser(path,defaultEncoding)){parser.TextFieldType=FieldType.Delimited;//设定逗号分隔符parser.SetDelimiters(",");//设定不忽略字段前后的空格parser.TrimWhiteSpace=false;boolisLine=false;while(!parser.EndOfData){string[]fields=parser.ReadFields();if(isLine){varobj=func(fields);if(obj!=null)list.Add(obj);}else{//忽略标题行业isLine=true;}}}returnlist;}#endregion#region读CSV文件(使用正则表达式)///<summary>///读CSV文件,默认第一行为标题///</summary>///<typeparamname="T"></typeparam>///<paramname="path">文件路径</param>///<paramname="func">字段解析规则</param>///<paramname="defaultEncoding">文件编码</param>///<returns></returns>publicstaticList<T>Read_Regex<T>(stringpath,Func<string[],T>func,EncodingdefaultEncoding=null)whereT:class{List<T>list=newList<T>();StringBuildersbr=newStringBuilder(100);RegexlineReg=newRegex("\"");RegexfieldReg=newRegex("\\G(?:^|,)(?:\"((?>[^\"]*)(?>\"\"[^\"]*)*)\"|([^\",]*))");RegexquotesReg=newRegex("\"\"");boolisLine=false;stringline=string.Empty;using(StreamReadersr=newStreamReader(path)){while(null!=(line=ReadLine(sr))){sbr.Append(line);stringstr=sbr.ToString();//一个完整的CSV记录行,它的双引号一定是偶数if(lineReg.Matches(sbr.ToString()).Count%2==0){if(isLine){varfields=ParseCsvLine(sbr.ToString(),fieldReg,quotesReg).ToArray();varobj=func(fields.ToArray());if(obj!=null)list.Add(obj);}else{//忽略标题行业isLine=true;}sbr.Clear();}else{sbr.Append(Environment.NewLine);}}}if(sbr.Length>0){//有解析失败的字符串,报错或忽略}returnlist;}//重写ReadLine方法,只有\r\n才是正确的一行privatestaticstringReadLine(StreamReadersr){StringBuildersbr=newStringBuilder();charc;intcInt;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);returnsbr.ToString();}else{sbr.Append(c);}}returnsbr.Length>0?sbr.ToString():null;}privatestaticList<string>ParseCsvLine(stringline,RegexfieldReg,RegexquotesReg){varfieldMath=fieldReg.Match(line);List<string>fields=newList<string>();while(fieldMath.Success){stringfield;if(fieldMath.Groups[1].Success){field=quotesReg.Replace(fieldMath.Groups[1].Value,"\"");}else{field=fieldMath.Groups[2].Value;}fields.Add(field);fieldMath=fieldMath.NextMatch();}returnfields;}#endregion}}

使用方法如下:

//写CSV文件CsvFile.Write(records,path,true,newFunc<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());}returnfields;}));//读CSV文件records=CsvFile.Read(path,Test.Parse);//读CSV文件records=CsvFile.Read_Regex(path,Test.Parse);
 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:C#如何实现读写CSV文件的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:PHP怎么才能获取真实IP下一篇:

40 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18