使用 SqlBulkCopy 批量從execl中匯入資料
阿新 • • 發佈:2019-01-09
string text11 = "E:/UserFile/201638114343778799.xls";
//批量從execl中匯入資料
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" +"Data Source=" + text11 + ";" +
"Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataTable resutDt = new DataTable();
resutDt.Columns.Add("Id", typeof(string));
resutDt.Columns.Add("realName", typeof(string));
resutDt.Columns.Add("userName", typeof(string));
resutDt.Columns.Add("email", typeof(string));
resutDt.Columns.Add("phone", typeof(string));
resutDt.Columns.Add("sex", typeof(bool));
resutDt.Columns.Add("remark", typeof(string));
try
{
da.Fill(ds);
dt = ds.Tables[0];
Console.WriteLine(dt.Rows.Count);
//this.dataGridView1.DataSource = dt;
SqlBulkCopy sqlbulk = new SqlBulkCopy(Db.strConn, SqlBulkCopyOptions.UseInternalTransaction);
sqlbulk.DestinationTableName = "資料庫表名";
DataRow dr;
foreach (DataRow item in dt.Rows)
{
dr = resutDt.NewRow();
dr[0] = Guid.NewGuid().ToString();
dr[1] = item[0];
dr[2] = item[1];
dr[3] = item[2];
dr[4] = item[3];
dr[5] = item[4].ToString().Equals("男") ? true : false;
dr[6] = item[5];
resutDt.Rows.Add(dr);
}
sqlbulk.WriteToServer(resutDt);
}
catch (Exception err)
{
throw;
// MessageBox.Show("操作失敗!" + err.ToString());
}
Console.WriteLine(strConn);
可以實現大批量的資料從excel表中匯入到資料庫表中