2012-01-11 5 views
0

私はSQLBulkCopyを読んでおり、ExcelドキュメントからSQL Serverに何千もの行をインポートするために使用したいと考えています。私はデータを変更せずに直接行う記事を読んでいます。 SQLBulkCopyを実行する前に、Excelドキュメントのデータに対していくつかの変更と検証を行う必要があります。これは可能ですか?私は過負荷から、データを変更して大きなサイズのDataTableを作成し、そのDataTableWriteToServerにインポートすると仮定します。ExcelをSQL Serverにコピーしてデータを変更する

答えて

1

インポートする前に検証/変更のために反復処理できるDataReaderまたはDataSetが必要な場合があります。

このユーティリティはあなたを助けるかもしれない - http://exceldatareader.codeplex.com/

+0

インポートする前に、ファイルの検証を行うことが可能であるようなので、それが見えます。 –

+0

はい、自分のデータセットプロバイダを使用して自分で作成しましたが、このツールを使用すると簡単になります。検証後、同じDataSetテーブルを使用してインポートを実行するか、別のSqlBulkCopyを使用して直接ファイルを処理できます。 – PinnyM

+0

ありがとうございます。一括挿入が失敗した場合にどのローがエラーを起こしているかを知る方法はありませんか? –

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(); 
    } 
関連する問題