0

我正在将 ExcelSheet 导入 SQL Server 数据库,我遇到的问题是 ExcelSheet 大约有 25 列,而数据库表有 15 行。我需要跳过 excel 中多余的不需要的行,例如:

using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{                  
   bulkCopy.ColumnMappings.Add("PP NO", "passportnumber");
   bulkCopy.ColumnMappings.Add("COVER NO", "covernumber");
   bulkCopy.ColumnMappings.Add("NAME", "paxname");
   .....
}

我得到的错误是 The given ColumnMapping does not match up with any column in the source or destination.

4

2 回答 2

1

ColumnMappings 区分大小写。Source Column name和Destination Column name拼写不一样,你也必须检查并在Tables中写入相同的列名。

于 2012-11-07T10:11:04.890 回答
0

请试试这个,让我知道状态

OdbcConnection connection;
SqlBulkCopy bulkCopy;
string ConnectionString = @"server=hostname\sqlexpress;database=pubs;uid=sa;pwd=1234;";
string connstr = @"Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=c:\contact.xls";
using (connection = new OdbcConnection(connstr))
{

OdbcCommand command = new OdbcCommand("Select * FROM [Sheet1$]", connection);

//you can change [Sheet1$] with your sheet name
connection.Open();

// Create DbDataReader to Data Worksheet

using (OdbcDataReader dr = command.ExecuteReader())

{

// Bulk Copy to SQL Server



using (bulkCopy = new SqlBulkCopy(ConnectionString))
{

 // I have given column name "id" in the excel and "empId" sql table, 

 bulkCopy.ColumnMappings.Add("id","empId");
 bulkCopy.ColumnMappings.Add("name","name");

    OR
// You can give index directly
 bulkCopy.ColumnMappings.Add(0,0);
 bulkCopy.ColumnMappings.Add(1,1);

bulkCopy.DestinationTableName = "Names";
//"Names" is the sql table where you want to copy all data
bulkCopy.WriteToServer(dr);
}
dr.Close();
}
}

bulkCopy.Close();
于 2012-11-07T10:08:48.303 回答