C# CSV檔案匯入資料庫
阿新 • • 發佈:2019-02-09
做CSV匯入資料庫,一般是採用逐行讀取,資料連線讀取,再有這個通過引用Microsoft.VisualBasic.FileIO.TextFieldParser
其它方法我沒試過,有朋友可以提示一下,非常感謝。逐行讀取方法比較傻,資料連線讀取效率高,通過TextFileParser這個方法比較特殊吧,今天剛發現,感覺不錯。
1.通過資料連線讀取
1: private void button1_Click(object sender, EventArgs e)
2: {
3: subImportCsv_Dataset("f:\\", "jjj.csv");
4: }
5: public void subImportCsv_Dataset(string filePath, string fileName)
6: {
7: string strConn = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=";
8: strConn += filePath;//這個地方只需要目錄就可以了
9: strConn += ";Extensions=asc,csv,tab,txt;";
10: OdbcConnection objConn = new OdbcConnection(strConn);
11: DataSet ds = new DataSet();
12: try
13: {
14: string strSQL = "select * from " + fileName;//檔名,不要帶目錄
15: OdbcDataAdapter da = new OdbcDataAdapter(strSQL, objConn);
16: da.Fill(ds);
17: //開始匯入資料庫
18:}
19: catch (Exception ex)
20: {
21: throw ex;
22: }
23: }
2.通過TextFileParser讀取
public class CSVHelper{
static public DataTable ReadCsv(string filepath)
{
DataTable dt = new DataTable("NewTable");
DataRow row;
Microsoft.VisualBasic.FileIO.TextFieldParser TF = new Microsoft.VisualBasic.FileIO.TextFieldParser(filepath, Encoding.GetEncoding("GB2312"));
int i = 0;
string[] strLine;
while (!TF.EndOfData)
{
try
{
TF.Delimiters = new string[] { "\t" };
strLine = TF.ReadFields();
if (i == 0)
{
for (int j = 0; j < strLine.Length; j++)
{
dt.Columns.Add(strLine[j]);
}
//新增加一列,這裡列的資料位空
dt.Columns.Add(Guid.NewGuid().ToString());
}
else
{
row = dt.NewRow();
row.ItemArray = strLine;
dt.Rows.Add(row);
}
i++;
}
catch (Exception ex)
{
throw ex;
}
}
TF.Close();
return dt;
}
}