2012-01-11 37 views
0

我正在阅读SQLBulkCopy并希望使用它将数千行从Excel文档导入到SQL Server。我一直在阅读直接做文章而不修改数据的文章。在执行SQLBulkCopy之前,我需要对Excel文档中的数据进行一些修改和验证。是否有可能做到这一点?我会从过载中假设我可以修改数据并创建一个大的DataTable,并用WriteToServer导入DataTable将Excel批量复制到SQL Server,但有数据修改

回答

1

您可能需要一个DataReader或DataSet,您可以在导入之前对其进行迭代以进行验证/修改。

此实用工具可以帮助你 - http://exceldatareader.codeplex.com/

+0

所以它看起来是有可能导入之前做的文件验证。 – 2012-01-11 18:38:28

+0

是的,我自己使用自己的DataSet提供程序完成了这个工作,尽管这个工具应该可以让它更容易。验证之后,您可以使用相同的DataSet表执行导入,也可以使用单独的SqlBulkCopy直接处理文件。 – PinnyM 2012-01-11 18:46:15

+0

谢谢。如果大容量插入失败,那么没有办法找出哪一行发生错误? – 2012-01-11 18:49:22

0

这对我工作得很好:

public ActionResult Create(HttpPostedFileBase file) 
    { 
     string strConnection = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString; 

     //file upload path 
     var fileName = Path.GetFileName(file.FileName); 
     // store the file inside ~/App_Data/uploads folder 
     var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); 
     file.SaveAs(path); 

     //Create connection string to Excel work book 
     string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;Persist Security Info=False"; 
     //Create Connection to Excel work book 
     OleDbConnection excelConnection = new OleDbConnection(excelConnectionString); 
     //Create OleDbCommand to fetch data from Excel 
     excelConnection.Open(); 
     DataTable dt = new DataTable(); 

     dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); 
     if (dt == null) 
     { 
      return null; 
     } 

     String[] excelSheets = new String[dt.Rows.Count]; 
     int t = 0; 
     //excel data saves in temp file here. 
     foreach (DataRow row in dt.Rows) 
     { 
      excelSheets[t] = row["TABLE_NAME"].ToString(); 
      t++; 
     } 

     OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString); 

     string query = string.Format("SELECT * FROM [{0}]", excelSheets[0]); 

     OleDbCommand cmd = new OleDbCommand(query, excelConnection); 
     //excelConnection.Open(); 
     OleDbDataReader dReader; 
     dReader = cmd.ExecuteReader(); 
     SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection); 
     //Give your Destination table name 
     sqlBulk.DestinationTableName = "[FSM].[DFS_Akustik]"; 
     sqlBulk.WriteToServer(dReader); 
     excelConnection.Close(); 

     ViewBag.view_dfs_akustik = dbman.View_DFS_Akustik.ToList(); 
     return View(); 
    } 
相关问题