有谁知道如何将csv文件的特定列转换为字符串List? 我正在尝试从csv文件中获取“联系号码”列表。 (请参阅下面的csv文件)
List<string> contactNumberList = new List<string>();
-- contactNumberList.Add("1888714"); (Manual)
---contactNumberList.Add("1888759");(Manual)
"Email","Opt In Date","Opted Out","Opt In Details","Email Type","Opted Out Date","Opt Out Details","Contact Number","Salutation"
"test1@testApp.com","05/01/2014 11:23 AM","F","User Name: capn@goldpop.org.uk. IP Address: 62.213.118.139","0","","","1888714","Mrs Hall"
"test2@testApp.com","05/01/2014 11:23 AM","F","User Name: capntransfer@goldpop.org.uk. IP Address: 62.213.118.139","0","","","1888759","Mrs Heyworth"
答案 0 :(得分:1)
为了解析CSV,我建议使用一个简单的文件,只需按行/列分隔符拆分,如果值被转义,就会带来错误。
即。
“约翰先生,鲍勃史密斯”
是有效的CSV,因为它使用引号进行转义。但是Split功能将停止工作。
一个有效的选择是LumenWorks(您可以在NuGet中找到它。)
即。
using (var csv = new CsvReader(r, false, csvParserConfiguration.ColumnSeparator, '"', '"', '#', ValueTrimmingOptions.None))
{
// Read lines
while (csv.ReadNextRecord())
{
contactNumberList.Add[7];
}
}
答案 1 :(得分:0)
逐行阅读文件,用逗号命名Split()
,选择所需的列,修剪引号并添加到列表中?
答案 2 :(得分:0)
试试这个:
int columnId = 3;
string[] lines = File.ReadAllLines(@"C:\test.csv");
var list = lines.Select(line =>
{ var values = line.Split(';');
return values[columnId];
});
答案 3 :(得分:0)
您可以尝试以下方法:
var reader = new StreamReader(File.OpenRead(@"C:\test.csv"));
List<string> contactNumbersList = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
contactNumbersList.Add(values[7]);
}
但更好的是你可以使用像CSV Reader这样的专用库。
答案 4 :(得分:0)
IEnumerable<string> strings = System.IO.File.ReadAllLines({filepath})
.Select(x => x.Split(';')[{columnId}])