我怎样才能将两个excel列在导入到数据库?

我想在excel中结合date和时间列,并使用sqlbulkcopy将其映射到数据库中的一列。 我收到一个错误:

date] [时间不匹配任何列映射

看到我下面的示例代码。 任何想法如何做到这一点,而不复制到数据表?

Dim sSourceConstr As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", sPath) Dim sDestConstr As String = ConfigurationManager.ConnectionStrings("SolCards").ConnectionString Dim sSourceConnection As New OleDbConnection(sSourceConstr) Using sSourceConnection Dim sql As String = String.Format("Select [Customer Cod],[Customer],[PAN],[Vehicle],[Date],[Station],[Driver],[Authorized],[Product]" & ", [Pump], [Tran No], [Odo], [Metric], [UPrice], [Qty], [Amount], [TimeFormat] FROM [{0}$]", "trans") Dim command As New OleDbCommand(sql, sSourceConnection) sSourceConnection.Open() Using dr As OleDbDataReader = command.ExecuteReader() Using bulkCopy As New SqlBulkCopy(sDestConstr) bulkCopy.DestinationTableName = "FuelInformation" 'column mapping bulkCopy.ColumnMappings.Add("[Date] [Time]", "DatePurchased") bulkCopy.WriteToServer(dr) End Using End Using End Using 

我解决这个问题的方法是使用excel的CONCATENATE实际公式。 您可以将其放入您的代码中,也可以在电子表格中添加一个新列并调用该单元格的值。

该错误的修复程序是:

  "Select ([date],[time])values(@date,@time)" bulkCopy.ColumnMappings.Add("@Date", "DatePurchased") bulkCopy.ColumnMappings.Add("@time", "DatePurchased") 

我通过使用CStr()来解决这个问题,结合两列的问题是列标题名称中有关键字。

  Dim sSourceConstr As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;""", sPath) Dim sDestConstr As String = ConfigurationManager.ConnectionStrings("SolCards").ConnectionString Dim sSourceConnection As New OleDbConnection(sSourceConstr) Using sSourceConnection Dim sql As String = String.Format("SELECT CStr([Date]) + ' ' + CStr([Time]) as [DatePurchased] ,[Customer Cod],[Customer],[PAN],[Vehicle],[Station],[Driver],[Authorized],[Product], [Pump], [Tran No], [Odo], [Metric], [UPrice], [Qty], [Amount], [TimeFormat] FROM [{0}$]", "trans") Dim command As New OleDbCommand(sql, sSourceConnection) sSourceConnection.Open() Using dr As OleDbDataReader = command.ExecuteReader() Using bulkCopy As New SqlBulkCopy(sDestConstr) bulkCopy.DestinationTableName = "FuelInformation" 'column mapping bulkCopy.ColumnMappings.Add("[DatePurchased]", "DatePurchased") bulkCopy.WriteToServer(dr) End Using End Using End Using