新手發帖,很多方面都是剛入門,有錯誤的地方請大家見諒,歡迎批評指正
C#讀取CSV檔案
很多項目中都要需操縱CSV檔案,我看到很多人都市編碼讀取CSV檔案中的第一行并釋解其中的個一每列的值,
相對來說這有難度,
一來要求開發人員對字元串處置比拟熟習,
二來要求對CSV的檔案結構要有當相的懂得,難度較大,編寫的碼代量質也要經過一段時間的磨練,
但其實有一種更單簡的方法,即用使微軟的本文驅動程式,以表的情勢來通路CSV檔案。
體具碼代如下所示
public DataTable GetCsvData(string filePath, string fileName)
{
string path = filePath + "\\" + fileName + ".csv";
string connString = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + filePath + ";Extensions=csv";
每日一道理
隻有啟程,才會到達理想和目的地,隻有拼搏,才會獲得輝煌的成功,隻有播種,才會有收獲。隻有追求,才會品味堂堂正正的人。
try
{
using (OdbcConnection odbcConn = new OdbcConnection(connString))
{
odbcConn.Open();
OdbcCommand oleComm = new OdbcCommand();
oleComm.Connection = odbcConn;
oleComm.CommandText = "select * from [" + fileName + "#csv]";
OdbcDataAdapter adapter = new OdbcDataAdapter(oleComm);
DataSet ds = new DataSet();
adapter.Fill(ds, fileName);
odbcConn.Close();
return ds.Tables[0];
}
}
catch (Exception ex)
throw ex;