我遇到了选择查询的问题。我的目标是在excel表中选择一些列并将它们复制到我的sql表中。我有六个colums要复制。当我因为标识栏而试图复制订单时发生了变化。
这是我的代码;
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 :(得分:0)
您应该使用SqlBulkCopy类的ColumnMappings属性。
代表:
sqlBulk.ColumnMappings.Add("column_1", "column_1");
sqlBulk.DestinationTableName = "MYtable";
答案 1 :(得分: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));
}