excel文件(xls)批量导入sqlserver数据库 用SqlBulkCopy方法批量导入效率高。
string tableName = "TD_GYTDSPF"; string[] fields = { "TDZH", "TDZL", "DLYT", "SYQLX", "FinishTime" }; string connectionString = "server=xxx;User ID=sa;Password=sa;database=xxx;Connection Reset=FALSE"; string connetctonExcel = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=e:\11.xls;Extended Properties=Excel 8.0;"; string filepath = @"e:\11.xlsx"; //把excel作为数据源,读取数据存在dataset中 DB.Database db = Database.GetDatabase(connetctonExcel); DataSet ds; db.ExecuteSQLQuery("SELECT * FROM [sheet1$] ", out ds); /* //建表及清空表数据。自动创建数据库表,读取的是csv文件,类似txt文件 string strSql = string.Format("if object_id('{0}') is null create table {0}(", tableName); for (int i = 0; i < fields.Length; i++) { strSql += string.Format("[{0}] varchar(255),", fields[i]); } strSql = strSql.Trim(',') + ");"; strSql += " truncate table " + tableName + ";"; using (SqlConnection sqlconn = new SqlConnection(connectionString)) { sqlconn.Open(); SqlCommand command = sqlconn.CreateCommand(); command.CommandText = strSql; command.ExecuteNonQuery(); sqlconn.Close(); } */ DataTable dt = new DataTable(); dt = ds.Tables[0]; /* using (StreamReader sr = new StreamReader(filepath)) { string[] value; DataRow row; for (int x = 0; x < fields.Length; x++) { dt.Columns.Add(new DataColumn(fields[x])); } while (!sr.EndOfStream) { value = sr.ReadLine().Split(','); row = dt.NewRow(); row.ItemArray = value; dt.Rows.Add(row); } sr.Close(); }*/ SqlConnection con = new SqlConnection(connectionString); SqlBulkCopy bc = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.TableLock); bc.DestinationTableName = tableName; //for (int i = 0; i < dtColum.Count; i++) //{ // bc.ColumnMappings.Add(dtColum[i].ColumnName.ToString(), dtColum[i].ColumnName.ToString()); //} bc.BatchSize = 10000; con.Open(); bc.WriteToServer(dt); bc.Close(); con.Close();