【问题标题】:How to properly read columns from text file如何正确读取文本文件中的列
【发布时间】:2012-07-16 07:32:45
【问题描述】:

我试图从文本文件中读取数据并将其加载到数据集中,但下图中的不同列只是一个长列。我想以 7 列的形式返回数据(与下图中显示的方式相同)。

这是我正在使用的代码,

public DataSet LoadTxtFile(int numberOfRows)
    {
        DataSet ds = new DataSet();
        //try
        //{
            // Creates and opens an ODBC connection
            string strConnString = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + this.dirCSV.Trim() + ";Extensions=asc,csv,tab,txt;Persist Security Info=False";
            string sql_select;
            OdbcConnection conn;
            conn = new OdbcConnection(strConnString.Trim());
            conn.Open();

            //Creates the select command text
            if (numberOfRows == -1)
            {
                sql_select = "select * from [" + this.FileNevCSV.Trim() + "]";
            }
            else
            {
                sql_select = "select top " + numberOfRows + " * from [" + this.FileNevCSV.Trim() + "]";
            }

            //Creates the data adapter
            OdbcDataAdapter obj_oledb_da = new OdbcDataAdapter(sql_select, conn);

            //Fills dataset with the records from CSV file
            obj_oledb_da.Fill(ds, "csv");

            //closes the connection
            conn.Close();
        //}
        //catch (Exception e) //Error
        //{
            //MessageBox.Show(e.Message, "Error - LoadCSV",MessageBoxButtons.OK,MessageBoxIcon.Error);
        //}
        return ds;
    }

【问题讨论】:

  • 什么语言,看起来像 Java/C#,但你应该适当地标记它。
  • 你的名字指向它是C#

标签: c#-4.0 text-files csv


【解决方案1】:

我通常采用一种简单的解决方案,即访问文件,读取所有行,在循环中拆分行字符串,创建并填充新的数据行,最后将数据行添加到数据表中:

string[] records = File.ReadAllLines(path);
foreach(string record in records)
{
  DataRow r = myDataTable.NewRow();
  string[] fields = record.Split('\t');
  /* Parse each field into the corresponding r column
   * ....
   */
  myDataTable.rows.Add(r);
}

我还找到了有关如何使用 OleDb 连接和架构信息文件访问 CSV 文件的解决方案。我从来没有使用过这种方法。

参考资料:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    • 2015-05-20
    • 2012-01-24
    • 2022-11-13
    相关资源
    最近更新 更多