[C#] 大量讀取csv檔

  • 25090
  • 0
  • C#
  • 2008-11-16

摘要:[C#] 大量讀取csv檔

方法一(使用Odbc):
首先電腦要有odbc的驅動檔案。

using System.Data.Odbc;

string str = Server.MapPath(".") + "\\temp\\";
OdbcConnection cn = new OdbcConnection(@"Driver={Microsoft Text Driver (*.txt; *.csv)};DBQ=" + str); //檔案所在的資料夾
OdbcCommand cmd = new OdbcCommand("select * from " + FileUpload1.FileName, cn); //FileUpload1.FileName就是檔案的名子就好,範例是結合上傳的檔案
OdbcDataAdapter da = new OdbcDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = cmd;
da.Fill(ds, "upload"); //這樣就可以轉成dataset了

方法二(使用OleDb):

using System.Data.OleDb;
string strPath = Server.MapPath(".") + "\\temp\\";
string ConnectionString =
string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties=""text;HDR=Yes;FMT=Delimited"";", strPath); //strPath是檔案所在的資料夾
string CommandText = string.Format(@"SELECT * FROM " + FileUpload1.FileName, ConnectionString);  //FileUpload1.FileName就是檔案的名子就好,範例是結合上傳的檔案
OdbcDataAdapter da = new OdbcDataAdapter();

DataSet CSVDataSet = new DataSet();
OleDbConnection CSVConnection = new OleDbConnection(ConnectionString);
OleDbDataAdapter CSVAdapter = new OleDbDataAdapter(CommandText, CSVConnection);
CSVConnection.Open();
CSVAdapter.Fill(CSVDataSet, "upload");
CSVConnection.Close();


 

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo