About green triangle indicator in Excel cells’ upper-left corner
Posted: August 6, 2009 Filed under: Excel 2003 Leave a commentImport from Excel to SQL Server through BulkCopy with ColumnMappings
Posted: April 3, 2009 Filed under: Excel 2003 Leave a comment
Here is a code snippet I copied from a question I answered at ASP.NET forum:
If the source columns are not matching with destination in position and/or name, you need to define ColumnMappings during the bulkcopy.
protected void Page_Load(object sender, EventArgs e)
{
// Connection String to Excel Workbook
string excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\property.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
// Create Connection to Excel Workbook
using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection(excelConnectionString))
{
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand
("Select CountyCode,PropertyAppraiserName FROM [county$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (System.Data.OleDb.OleDbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=.; Database=test_for_forum;Integrated Security=True";
// Bulk Copy to SQL Server
using (System.Data.SqlClient.SqlBulkCopy bulkCopy = new System.Data.SqlClient.SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "tblPropertyAppraiser";
//Define ColumnMappings: source –destination
bulkCopy.ColumnMappings.Add("CountyCode", "DesCountyCode");
bulkCopy.ColumnMappings.Add("DesPropertyAppraiserName", "PropertyAppraiserName");
bulkCopy.WriteToServer(dr);
}
}
}
}