【问题标题】:Ignore the comma inside a row from a csv [duplicate]忽略csv中一行内的逗号[重复]
【发布时间】:2013-03-28 13:16:30
【问题描述】:

所以这是我的问题。

我正在将 CSV 读入数据网格视图。 csv 的第一行是列标题,文件的第一行是行。我正在读取文件并用作 datagridview 的数据源。但是 CSV 中的某些行类似于

name,test,1,2,3,test,2,3,2,1,test,name

当我使用.Split() 时,上面加粗的地方将其视为行中的一个新单元格,但是列数是 10 而不是 11,我收到以下错误:

输入数组长于该表的列数

我怎样才能解决这个问题。

下面是我的 C# 代码。

OpenFileDialog openFile = new OpenFileDialog();
        openFile.InitialDirectory = "c:\\";
        openFile.Filter = "txt files (*.txt)|*.txt| CSV Files (*.csv) | *.csv| All Files (*.*) | *.*";
        openFile.FilterIndex = 2;
        openFile.RestoreDirectory = true;
        try {
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                string file = openFile.FileName;
                StreamReader sr = new StreamReader(file);

                /* gets all the lines of the csv */
                string[] str = File.ReadAllLines(file);

                /* creates a data table*/
                DataTable dt = new DataTable();

                /* gets the column headers from the first line*/
                string[] temp = str[0].Split(',');

                /* creates columns of the gridview base on what is stored in the temp array */
                foreach (string t in temp)
                {
                    dt.Columns.Add(t, typeof(string));
                }

                /* retrieves the rows after the first row and adds it to the datatable */
                for (int i = 1; i < str.Length; i++)
                {
                    string[] t = str[i].Split(',');
                    dt.Rows.Add(t);
                }

                /* assigns the data grid view a data source based on what is stored in dt  */
                dataGridView1.DataSource = dt;
            }
        }
        catch (Exception ex) 
        {
                MessageBox.Show("Error: The CSV you selected could not be loaded" + ex.Message);
        }

【问题讨论】:

  • @SteveWellens 那是关于引号内的逗号。这里似乎没有任何引号,除非 OP 忘记了它们。

标签: c# csv datagridview datatable datasource


【解决方案1】:

这听起来更像是数据问题而不是编程问题。如果您的 CSV 文件应该有 10 列,但有些有 11 列,那么您如何知道哪一列是多余的列?

您可以做的一件事是在添加行之前检查列数。

for (int i = 1; i < str.Length; i++)
{
    string[] t = str[i].Split(',');
    if(t.Length == temp.Length)
        dt.Rows.Add(t);
}

【讨论】:

    猜你喜欢
    • 2022-01-08
    • 2017-08-08
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多