讀取CSV檔案的幾種方式

來源:互聯網
上載者:User

只做記錄,沒做過詳細分析,用過資料連線,貌似還不錯,別的方法沒用過。

1.資料連線方式:

根據串連方式的不同,又分成幾種:

  • ODBC方式:會自動將第一行作為行頭去掉,而且無法設定不去掉第一行。
代碼

  /// <summary>
/// 擷取CSV匯入的資料,不帶尾碼名
/// </summary>
/// <param name="filePath">檔案路徑</param>
/// <param name="fileName">檔案名稱(.csv不用加)</param>
/// <returns></returns>
public DataTable GetCsvData(string filePath, string fileName)
{
string path = Path.Combine(filePath, fileName);
string connString = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + filePath + ";Extensions=asc,csv,tab,txt;";
try
{
using (OdbcConnection odbcConn = new OdbcConnection(connString))
{
odbcConn.Open();
OdbcCommand oleComm = new OdbcCommand();
oleComm.Connection = odbcConn;
oleComm.CommandText = "select * from [" + fileName + "]";
OdbcDataAdapter adapter = new OdbcDataAdapter(oleComm);
DataSet ds = new DataSet();
adapter.Fill(ds, fileName);
odbcConn.Close();
_dataSource = ds.Tables[0];
return _dataSource;
}
}
catch (Exception ex)
{
throw ex;
}
}
  • OleDb方式,可以設定是否忽略第一行,HDR=Yes則忽略第一行。

 

代碼

   connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+filePath+";Extended Properties='text;HDR=No;FMT=Delimited'";
try {
using (OleDbConnection oledbConn = new OleDbConnection(connString))
{
oledbConn.Open();
OleDbCommand oleComm = new OleDbCommand();
oleComm.Connection = oledbConn;
oleComm.CommandText = "select * from [" + fileName + "]";
OleDbDataAdapter adapter = new OleDbDataAdapter(oleComm);
DataSet ds = new DataSet();
adapter.Fill(ds, fileName);
oledbConn.Close();
_dataSource = ds.Tables[0];
return ds.Tables[0];
}
}

 

 

經測試,這兩種方法都可以,不知道有沒有差別。

具體資料連線方式參見:http://www.connectionstrings.com/textfile

 

2.檔案流方式:

代碼

  public static List<String[]> ReadCSV(string filePathName)
{
List<String[]> ls = new List<String[]>();
StreamReader fileReader=new StreamReader(filePathName);
string strLine="";
while (strLine != null)
{
strLine = fileReader.ReadLine();
if (strLine != null && strLine.Length>0)
{
ls.Add(strLine.Split(','));
}
}
fileReader.Close();
return ls;
}

3.TextFileParser的方式:

代碼

  private void subImportCSV_FileIo(string strFile)
{
Microsoft.VisualBasic.FileIO.TextFieldParser TF = new Microsoft.VisualBasic.FileIO.TextFieldParser(strFile, Encoding.GetEncoding("GB2312"));
TF.Delimiters = new string[] { "," }; //設定分隔字元
string[] strLine;
while (!TF.EndOfData)
{
try
{
strLine = TF.ReadFields();
//開始匯入資料庫,這個地方要排除行頭
}
catch
{
}
}
TF.Close();
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.