如何正确读取文本文件中的列 [英] How to properly read columns from text file

查看:290
本文介绍了如何正确读取文本文件中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从文本文件中读取数据并将其加载到数据集中,但下图中的不同列只显示为一个长列。我想要返回的数据为7列(与它出现在下面的图像相同)。

Im trying to read data from a text file and loading it into a dataset but the different columns as in the image below are coming as just one long column. I want to return the data as 7 columns (in the same way as its appearing in the image below).

这是我使用的代码,

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;
    }

推荐答案

我通常采用一个平凡的解决方案,文件,我读取所有行,在循环中我拆分行字符串,创建和填充一个新的数据行,最后我添加数据行到数据表:

I usually adopt a trivial solution, i.e. I access the file, I read all lines, in a loop I split the line string, create and populate a new datarow, and finally I add the data row to the datatable:

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文件的解决方案,模式信息文件。我从未使用过这种方法。

I have also found solutions regarding how to access CSV files with OleDb connections, and schema information files. I have never used this approach.

参考文献:

  • File.ReadAllLInes().
  • String.Split().
  • Stackoverflow related question with OleDb connection.
  • MSDN Schema Information File.

这篇关于如何正确读取文本文件中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆