65.9K
CodeProject 正在变化。 阅读更多。
Home

使用C#读取CSV文件

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (5投票s)

2013 年 10 月 11 日

CPOL
viewsIcon

46320

我将解释如何使用 C# 从 CSV 文件中提取数据。首先,你需要声明两个字符串变量及其属性来存储目录。

我将解释如何使用 C# 从 CSV 文件中提取数据。

首先,你需要声明两个字符串变量及其属性,用于存储要提取数据的 CSV 文件的目录和文件名。

private string dirCSV;
private string fileNevCSV;

public string FileNevCSV
{
 get{return fileNevCSV;}
 set{fileNevCSV=value;}
}

public string dirCSV
{
 get{return dirCSV;}
 set{dirCSV=value;}
} 
在第二步中,连接到数据源并将其填充到数据集中。
public DataSet loadCVS(int noofrows)
        {
            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 (noofrows == -1)
                {
                    sql_select = "select * from [" + this.FileNevCSV.Trim() + "]";
                }
                else
                {
                    sql_select = "select top " + noofrows + " * 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
            {
            }
            return ds;
        } 

在第三步中,从生成的 DataSet 中提取数据到 DataTable。

   this.dirCSV = "file path";
   this.fileNevCSV ="file name";

   DataSet ds = loadCVS(-1);
   DataTable table = ds.Tables[0];

   foreach (DataRow row in table.Rows)
      {
        //iterate through the DataTable.
      }

谢谢。
编码愉快!

© . All rights reserved.