0

我正在尝试解析带有数据的 CSV 文件,但没有成功,我在网上尝试了一堆工具,但没有一个能够正确解析 CSV 文件。我对我在这里寻求帮助这一事实感到困惑,因为有人会认为解析 CSV 数据会非常容易。

CSV 数据的格式如下:

",95,54070,3635,""Test Reservation"",0,102,0.00,0.00,2014-12-31,""Name of customer"",""$12.34 + $10, special price"",""extra information"",,CustomerName,,,,,1234567890,youremail@domain.com,CustomerName,2014-12-31,23:59:59,16,0,60,2,120,0,NULL,NULL,NULL,"

当前代码:

private void btnOpenFileDialog_Click(object sender, EventArgs e)
    {
        DialogResult result = openFileDialog1.ShowDialog();

        if (result == DialogResult.OK)
        {
            using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
            {
                string line;

                while ((line = reader.ReadLine()) != null)
                {
                    ParseCsvLine(line);
                }
            }
        }
    }

    private void ParseCsvLine(string line)
    {
        if (line != string.Empty)
        {
            string[] result;

            using (var csvParser = new TextFieldParser(new StringReader(line)))
            {
                csvParser.Delimiters = new string[] { "," };

                result = csvParser.ReadFields();
            }

            foreach (var item in result)
            {
                Console.WriteLine(item + Environment.NewLine);
            }
        }
    }

结果变量只有一项及其:

,95,54070,3635,"Test Reservation",0,102,0.00,0.00,2014-12-31,"Name of customer","$12.34 + $10, special price","extra information",,CustomerName,,,,,1234567890,youremail@domain.com,CustomerName,2014-12-31,23:59:59,16,0,60,2,120,0,NULL,NULL,NULL,
4

2 回答 2

0
// Add Microsoft.VisualBasic.dll to References.
using Microsoft.VisualBasic.FileIO; 

// input is your original line from csv.

// Remove starting and ending quotes.
input = input.Remove(0, 1);
input = input.Remove(input.Length - 1);

// Replace double quotes with single quotes.
input = input.Replace("\"\"", "\"");

string[] result;
using (var csvParser = new TextFieldParser(new StringReader(input)))
{
    csvParser.Delimiters = new string[] { "," };
    result = csvParser.ReadFields();
}   
于 2014-11-24T11:25:56.290 回答
0

您可以查看之前的一篇文章,该文章处理 csv 文件中那些讨厌的逗号。我在这里链接它。

此外,Mihai,您的解决方案仅适用于一行,但一旦有很多行要解析,就会失败。

于 2014-11-24T11:42:35.950 回答