csv文件去掉最后的逗号_处理CSV文件中的逗号

正如其他人所说,您需要转义包含引号的值。这里有一个C♯中的csv阅读器,它支持引用的值,包括嵌入引号和回车。

顺便说一下,这是经过单元测试的代码。我现在发布它,因为这个问题似乎出现了很多,而其他人可能不想要一个完整的库,而简单的CSV支持就行了。

您可以使用它如下:using System;public class test{

public static void Main()

{

using ( CsvReader reader = new CsvReader( "data.csv" ) )

{

foreach( string[] values in reader.RowEnumerator )

{

Console.WriteLine( "Row {0} has {1} values.", reader.RowIndex, values.Length );

}

}

Console.ReadLine();

}}

这是课程。注意,您可以使用Csv.Escape函数来编写有效的CSV。using System.IO;using System.Text.RegularExpressions;public sealed class CsvReader : System.IDisposable{

public CsvReader( string fileName ) : this( new FileStream( fileName, FileMode.Open, FileAccess.Read ) )

{

}

public CsvReader( Stream stream )

{

__reader = new StreamReader( stream );

}

public System.Collections.IEnumerable RowEnumerator

{

get {

if ( null == __reader )

throw new System.ApplicationException( "I can't start reading without CSV input." );

__rowno = 0;

string sLine;

string sNextLine;

while ( null != ( sLine = __reader.ReadLine() ) )

{

while ( rexRunOnLine.IsMatch( sLine ) && null != ( sNextLine = __reader.ReadLine() ) )

sLine += "\n" + sNextLine;

__rowno++;

string[] values = rexCsvSplitter.Split( sLine );

for ( int i = 0; i 

values[i] = Csv.Unescape( values[i] );

yield return values;

}

__reader.Close();

}

}

public long RowIndex { get { return __rowno; } }

public void Dispose()

{

if ( null != __reader ) __reader.Dispose();

}

//============================================

private long __rowno = 0;

private TextReader __reader;

private static Regex rexCsvSplitter = new Regex( @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))" );

private static Regex rexRunOnLine = new Regex( @"^[^""]*(?:""[^""]*""[^""]*)*""[^""]*$" );}public static class Csv{

public static string Escape( string s )

{

if ( s.Contains( QUOTE ) )

s = s.Replace( QUOTE, ESCAPED_QUOTE );

if ( s.IndexOfAny( CHARACTERS_THAT_MUST_BE_QUOTED ) > -1 )

s = QUOTE + s + QUOTE;

return s;

}

public static string Unescape( string s )

{

if ( s.StartsWith( QUOTE ) && s.EndsWith( QUOTE ) )

{

s = s.Substring( 1, s.Length - 2 );

if ( s.Contains( ESCAPED_QUOTE ) )

s = s.Replace( ESCAPED_QUOTE, QUOTE );

}

return s;

}

private const string QUOTE = "\"";

private const string ESCAPED_QUOTE = "\"\"";

private static char[] CHARACTERS_THAT_MUST_BE_QUOTED = { ',', '"', '\n' };}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值