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表中导入到数据库表中