如何拆分列可能包含的csv

如何拆分列可能包含的csv

本文介绍了如何拆分列可能包含的csv,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




如何使用C#将上述信息拆分为以下字符串:

  2 
1016
7/31/2008 14:22
Geoff Dalgas
6/5/2011 22:21
http://stackoverflow.com
Corvallis,OR
7679
351
81
b437f461b3fd27387c5d8ab47a293d35
34

您可以看到其中一列包含< =(Corvallis,OR)



//更新//
基于

  string [] result = Regex.Split(samplestring,,(?=(?:[^ \] * \ [^ \] * \)* [^ \] * $)); 


解决方案

使用 Microsoft.VisualBasic.FileIO.TextFieldParser 类。这将处理解析分隔的文件 TextReader Stream ,其中一些字段用引号括起来,有些不是。



例如:

 使用Microsoft.VisualBasic.FileIO; 

string csv =2,1016,7 / 31/2008 14:22,Geoff Dalgas,2011年6月5日22:21,http://stackoverflow.com,\Corvallis, ,7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34;

TextFieldParser parser = new TextFieldParser(new StringReader(csv));

//你也可以从文件中读取
// TextFieldParser parser = new TextFieldParser(mycsvfile.csv);

parser.HasFieldsEnclosedInQuotes = true;
parser.SetDelimiters(,);

string [] fields;

while(!parser.EndOfData)
{
fields = parser.ReadFields();
foreach(字段中的字符串字段)
{
Console.WriteLine(field);
}
}

parser.Close();

这将导致以下输出:

 
2
1016
7/31/2008 14:22
Geoff Dalgas
6/5/2011 22:21
http ://stackoverflow.com
Corvallis,OR
7679
351
81
b437f461b3fd27387c5d8ab47a293d35
34

请参见 Microsoft。



您需要添加对 Microsoft.VisualBasic的引用在添加引用.NET选项卡中。


Given

How to use C# to split the above information into strings as follows:

2
1016
7/31/2008 14:22
Geoff Dalgas
6/5/2011 22:21
http://stackoverflow.com
Corvallis, OR
7679
351
81
b437f461b3fd27387c5d8ab47a293d35
34

As you can see one of the column contains , <= (Corvallis, OR)

// update //Based onC# Regex Split - commas outside quotes

string[] result = Regex.Split(samplestring, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
解决方案

Use the Microsoft.VisualBasic.FileIO.TextFieldParser class. This will handle parsing a delimited file, TextReader or Stream where some fields are enclosed in quotes and some are not.

For example:

using Microsoft.VisualBasic.FileIO;

string csv = "2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,\"Corvallis, OR\",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34";

TextFieldParser parser = new TextFieldParser(new StringReader(csv));

// You can also read from a file
// TextFieldParser parser = new TextFieldParser("mycsvfile.csv");

parser.HasFieldsEnclosedInQuotes = true;
parser.SetDelimiters(",");

string[] fields;

while (!parser.EndOfData)
{
    fields = parser.ReadFields();
    foreach (string field in fields)
    {
        Console.WriteLine(field);
    }
}

parser.Close();

This should result in the following output:

2
1016
7/31/2008 14:22
Geoff Dalgas
6/5/2011 22:21
http://stackoverflow.com
Corvallis, OR
7679
351
81
b437f461b3fd27387c5d8ab47a293d35
34

See Microsoft.VisualBasic.FileIO.TextFieldParser for more information.

You need to add a reference to Microsoft.VisualBasic in the Add References .NET tab.

这篇关于如何拆分列可能包含的csv,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 19:42