我使用vb.net将数据从Excel导入SQL Server数据库。在我的Excel文件的bNumber
列中,有不同类型的值,有些是数字,有些是文本:
Telenorx
Telenorx
8
97150219924
97150219924
97150219924
97150219924
Easypayx
92
当我通过OleDbCommand
从Excel中选择数据时,它会正确检索数字,但文本值为空白。
在Excel中,列的数据类型为General
。
这是我从Excel检索数据的代码。
excelConn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source= " + OpenFileDialog1.FileName + ";Extended Properties=""Excel 12.0
Xml;HDR=Yes""")
Dim oleDbCommand As OleDbCommand = New OleDbCommand("Select bNumber from
[Sheet1$]", excelConn)
excelConn.open()
Dim dataReader = oleDbCommand.ExecuteReader
dataReader.read()
答案 0 :(得分:1)
这不一定是你的案例的解决方案但我会创建一个bNumber为nvarchar的SQL-Server表,使用SQL-Server Management Studio导出到Excel,我将Excel文件放在bin \ Debug文件夹中该项目。使用下面的代码正确返回所有行(因为我们返回了一个字符串列字符串)。
这里的关键是在连接字符串中使用IMEX = 1,Excel可能很挑剔,这可能会也可能不会解决问题。
Imports System.Data.OleDb
Public Class Operations
Public Function GetData(ByVal FileName As String) As List(Of String)
Dim valueList As New List(Of String)
Using cn As New OleDbConnection With
{
.ConnectionString = ConnectionString(FileName)
}
Using cmd As OleDbCommand = New OleDbCommand("SELECT bNumber FROM [Table_1$]", cn)
cn.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader
While reader.Read
valueList.Add(reader.GetString(0))
End While
End Using
End Using
Return valueList
End Function
Public Function ConnectionString(ByVal FileName As String) As String
Dim Builder As New OleDbConnectionStringBuilder
If IO.Path.GetExtension(FileName).ToUpper = ".XLS" Then
Builder.Provider = "Microsoft.Jet.OLEDB.4.0"
Builder.Add("Extended Properties", "Excel 8.0;IMEX=1;HDR=Yes;")
Else
Builder.Provider = "Microsoft.ACE.OLEDB.12.0"
Builder.Add("Extended Properties", "Excel 12.0;IMEX=1;HDR=Yes;")
End If
Builder.DataSource = FileName
Return Builder.ConnectionString
End Function
End Class
表格代码
Private Sub Button3_Click(sender As Object, e As EventArgs) _
Handles Button3.Click
Dim ops As New Operations
Dim fileName As String = IO.Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, "Downloaded.xlsx")
Dim valueList As List(Of String) = ops.GetData(fileName)
For Each value As String In valueList
Console.WriteLine(value)
Next
End Sub
IDE输出窗口中的结果
表格结构
工作表
编辑:以下链接指向使用SpreadSheetLight库的MSDN代码示例。下载后,将启动表单设置为StackOverFlow1QuestionMixedTypesForm。右键单击解决方案资源管理器中的解决方案,然后选择“还原NuGet包”,现在构建并运行该项目。表单上有两个按钮,第一个是Sheet1的混合类型,而第二个按钮是Sheet2中不同布局的相同数据的变体。
代码示例https://code.msdn.microsoft.com/Alternate-methods-to-work-4c52c4a2