【问题标题】:C#: How do i select columns of data from csv, stored in an array/datatable?C#:如何从 csv 中选择数据列,存储在数组/数据表中?
【发布时间】:2012-07-03 10:20:17
【问题描述】:

我已成功将一个 .csv 文件加载到一个数组中,我将其设置为数据集/datagridview 控件以供查看。我一直遇到的问题是想办法:

  • 选择导入数据的列(根据 UI)
  • 存储新选择的信息以供审核

我拥有的当前代码允许用户在他们的系统上浏览文件并将数据存储在数组中并将其设置到数据表中。

    private void btnBrowse_Click(object sender, EventArgs e)
    {
        #region Local Variables
        int nRows = 0;      //Row Counter
        int icol = 0;       //Index value for Columns -> fArray
        int irow = 0;       //Index value for Row -> fArray
        string Line;        //Temp string value for storing lines
        #endregion

        #region File Open Parameters
        //file open parameters
        OpenFileDialog fopen = new OpenFileDialog();
        fopen.Title = "Choose file...";
        fopen.Filter = "Comma Seperated Values|*.csv";
        fopen.InitialDirectory = @"C:\";
        #endregion

        if (fopen.ShowDialog() == DialogResult.OK) //Show file open dialog and check if ok has been pressed
        {
            #region progress bar initialisation
            //initialize progress bar
            pb.Location = new Point(60, 209);
            pb.Width = 516;
            pb.Height = 23;
            pb.Style = ProgressBarStyle.Continuous;
            pnlStep1.Controls.Add(pb);
            #endregion

            try
            {
                StreamReader fReader = new StreamReader(fopen.FileName);

                #region Array Index Counters
                //Count Columns for fArray index
                string count = fReader.ReadLine();
                string[] tmpCount = count.Split(',');
                fReader.Close();

                //Count Rows for fArray index
                fReader = new StreamReader(fopen.FileName); //begin reading from line 1
                while ((fReader.ReadLine()) != null)
                {
                    nRows++;
                }

                fArray = new string[nRows, tmpCount.Length];
                fReader.Close();
                //End count
                #endregion

                #region Load File Contents
                fReader = new StreamReader(fopen.FileName); //begin reading from line 1
                DataSet ds = new DataSet();
                dt = ds.Tables.Add("ImportData");

                while ((Line = fReader.ReadLine()) != null)
                {
                    string[] row = Line.Split(',');
                    foreach (string column in row)
                    {
                        fArray[irow, icol] = column;
                        icol++;
                    }
                    icol = 0;
                    recordCountLabel.Text = irow.ToString(); //NEEDS LOOKING AT
                    pb.Value = (irow * 100) / fArray.GetLength(0);
                    irow++;
                }
                pb.Value = 100;
                fReader.Close();
                #endregion

                #region Add data to dgImport
                for (int i = 0; i < fArray.GetLength(1); i++) //Add Columns to empty DataGridView
                {
                    dt.Columns.Add("Field " + i.ToString());
                }

                for (int i = 0; i < 3; i++) //Insert data into DataGridView (use fArray.GetLength(0) for entire database or use 5 for sample data)
                {
                    DataRow row = dt.NewRow();
                    for (int j = 0; j < fArray.GetLength(1); j++)
                    {
                        row[j] = fArray[i, j].Trim();
                    }
                    dt.Rows.Add(row);
                    dgImport.DataSource = dt;
                }

                btnNext2.Enabled = true;
                #endregion

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk.\r\nOriginal error: " + ex.Message);
            }
        }   
    }

任何帮助将不胜感激:)。

编辑:对不起,我又忘了提及,我在 datagridview 控件中显示了一些示例数据行,并正在考虑提供动态创建的复选框列表,以允许用户勾选他/她想要的列选择(基本上只复制选定的数据)。

【问题讨论】:

  • 或者使用linq;比 oledb 快得多

标签: c# csv datagridview datatable


【解决方案1】:

您需要使用OleDb Provider 读取csv。这样您就可以指定要包含在SELECT 语句中的列集。

编辑:

 string location=@"c:\folder\";
 string cnstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + location + ";Extended Properties=\"text;HDR=No;FMT=Delimited\";";
 string sql = "select F2,F1 from test.csv";

 using (OleDbDataAdapter adp = new OleDbDataAdapter(sql, cnstr))
  {
    DataTable dt = new DataTable();
    adp.Fill(dt);

    foreach (DataRow row in dt.Rows)
    {
       Console.WriteLine(row[0] + " " + row[1]);
    }
  }

【讨论】:

  • 部分要求是客户可能并不总是定义列标题,这让我有点反对这个想法。
  • 您可以指定列别名F1(第一列),F2选择列。
猜你喜欢
  • 2011-10-10
  • 2016-06-19
  • 1970-01-01
  • 1970-01-01
  • 2022-09-22
  • 2019-03-04
  • 2020-02-23
  • 1970-01-01
  • 2019-07-09
相关资源
最近更新 更多