包含逗号的单元格的CSV文件,将数据读入C#程序

时间:2018-08-02 09:40:26

标签: c# csv

我正在编写一个程序以读取CSV文件并验证数据。 csv文件以逗号分隔。

csv文件包含在线检索的销售订单,因此我们实际上无法编辑CSV文件本身。我需要读入文件并将其拆分为单元格。但是,产品说明中将包含更多逗号,这将影响我访问数据的方式。

下面是我提取值的代码。

private void csvParse()
    {
        List<string> products = new List<string>();
        List<string> quantities = new List<string>();
        List<string> price = new List<string>();

        using (var reader = new StreamReader(txt_filePath.Text.ToString()))
        {
            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                var values = line.Split(',');

                products.Add(values[0]);
                quantities.Add(values[2]);

                values[3] = values[3].Substring(4);
                price.Add(values[3]);
            }
        }
        if (validateData(products, quantities, price) != "")
        {
            MessageBox.Show(validateData(products, quantities, price));
        }
    }

无论如何,是否会忽略设置单元格中的列,还是可以用另一个定界符区分这些列?

下面是我的csv文件中一行的摘要。

enter image description here

原始CSV数据如下:

TO12345,"E45 Dermatological Moisturising Lotion, 500 ml",765,GBP 1.75

3 个答案:

答案 0 :(得分:2)

您可以从nuGet中使用LinqToCSV。即:

void Main()
{
    List<MyData> sample = new List<MyData> {
        new MyData {Id=1, Name="Hammer", Description="Everything looks like a nail to a hammer, doesn't it?"},
        new MyData {Id=2, Name="C#", Description="A computer language."},
        new MyData {Id=3, Name="Go", Description="Yet another language, from Google, cross compiles natively."},
        new MyData {Id=3, Name="BlahBlah"},
    };
    string fileName = @"c:\temp\MyCSV.csv";

    File.WriteAllText(fileName,"Id,My Product Name,Ignore1,Ignore2,Description\n");
    File.AppendAllLines(fileName, sample.Select(s => $@"{s.Id},""{s.Name}"",""ignore this"",""skip this too"",""{s.Description}"""));

    CsvContext cc = new CsvContext();

    CsvFileDescription inputFileDescription = new CsvFileDescription
    {
        SeparatorChar = ',',
        FirstLineHasColumnNames = true, 
        IgnoreUnknownColumns=true
    };

    IEnumerable<MyData> fromCSV = cc.Read<MyData>(fileName, inputFileDescription);

    foreach (var d in fromCSV)
    {
        Console.WriteLine($@"ID:{d.Id},Name:""{d.Name}"",Description:""{d.Description}""");
    }
}

public class MyData
{
    [CsvColumn(FieldIndex = 1, Name="Id", CanBeNull = false)]
    public int Id { get; set; }
    [CsvColumn(FieldIndex = 2, Name="My Product Name",CanBeNull = false, OutputFormat = "C")]
    public string Name { get; set; }
    [CsvColumn(FieldIndex = 5, Name="Description",CanBeNull = true, OutputFormat = "C")]
    public string Description { get; set; }
}

答案 1 :(得分:0)

它应该工作..:)

var csvSplit = new Regex("(?:^|,)(\"(?:[^\"]+|\"\")*\"|[^,]*)", RegexOptions.Compiled);
            string[] csvlines = File.ReadAllLines(txt_filePath.Text.ToString());

            var query = csvlines.Select(csvline => new
            {
                data = csvSplit.Matches(csvline)
            }).Select(t => t.data);

            var row = query.Select(matchCollection =>
                (from Match m in matchCollection select (m.Value.Contains(',')) ? m.Value.Replace(",", "") : m.Value)
                .ToList()).ToList();

答案 2 :(得分:0)

您还可以使用 Microsoft.VisualBasic.FileIO.TextFieldParser 类。更详细的答案在这里:TextFieldParser