[英]How can i skip extra rows in excel while importing it into database using SqlBulkCopy?
我正在將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.
ColumnMappings區分大小寫。 源列名稱和目標列名稱的拼寫不相同,因此您還必須在表中檢查並寫入相同的列名稱。
請嘗試這個,讓我知道狀態
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.