2012-08-03 3 views
0

我有一個選擇查詢的問題。我的目標是選擇Excel表中的一些列,並將其複製到我的SQL表中。我有六個colums來複制。當我試圖複製因身份列而改變的訂單時。選擇查詢在excel表

這是我的代碼;

string path = Server.MapPath(Session["excel_sheet"].ToString()); 
     //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 
     OleDbCommand cmd2 = new OleDbCommand("Select [column_1],[column_2],[column_3],[column_4],[column_5],[column_6] from [Sheet1$]", excelConnection); 
     excelConnection.Open(); 
     OleDbDataReader dReader; 
     dReader = cmd2.ExecuteReader(); 
     SqlBulkCopy sqlBulk = new SqlBulkCopy(con); 
     //Give your Destination table name 
     sqlBulk.DestinationTableName = "MYtable"; 
     sqlBulk.WriteToServer(dReader); 
     excelConnection.Close(); 

我的表中有這樣identity_column,COLUMN_1,COLUMN_2,column_3,column_4,column_5,column_6列。

在excel column_4中拷貝例如字符串後寫入sql column_3,它必須寫入column_4。我在回答一個問題

回答

0

您可以通過列循環並將其映射,這將在連接在Excel中相同名稱的列名映射(即Excel的COLUMN_1 = SQL COLUMN_1)

SqlBulkCopy sqlBulk = new SqlBulkCopy(con); 
     //Define column mappings 

    for (int i = 0; i < dReader.FieldCount; i++) 
    { 
     sqlBulk.ColumnMappings.Add(dReader.GetName(i), dReader.GetName(i)); 
    } 
0

您應該使用SqlBulkCopy類的ColumnMappings屬性。

爲前:

sqlBulk.ColumnMappings.Add("column_1", "column_1"); 

sqlBulk.DestinationTableName = "MYtable";