1. 程式人生 > >C# 將Excel中的資料匯入到資料庫SQLS

C# 將Excel中的資料匯入到資料庫SQLS

解決方式: 1.現將Excel中的資料存放在DataTable中 程式碼參考部落格:C#讀取Excel中的內容,並將內容存放在二維陣列中” 2. 將DataTable中的資料匯入到SqlServer中 在這裡插入圖片描述 具體程式碼如下: public static void DataTableToSQLServer(DataTable dt) { string connectionString = @“Persist Security Info=False;Initial Catalog=dbname;Data Source=172.11.111.111; User ID=sa; Password=pwd”; using (SqlConnection destinationConnection = new SqlConnection(connectionString)) { destinationConnection.Open(); using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection)) { try { bulkCopy.DestinationTableName = “callLog”;//要插入的表的表名 bulkCopy.BatchSize = dt.Rows.Count; bulkCopy.ColumnMappings.Add(“id”, “id”);//表中的欄位名 第一個“id”是dt中的欄位名,第二個“id”表中的欄位名 bulkCopy.ColumnMappings.Add(“note_id”, “note_id”); bulkCopy.ColumnMappings.Add(“call_start_at”, “call_start_at”); bulkCopy.WriteToServer(dt); System.Windows.Forms.MessageBox.Show(“插入成功:”+ dt.Rows.Count+“行”); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } }