Connectionstring属性尚未初始化vb.net

时间:2015-02-16 10:14:14

标签: sql-server vb.net excel visual-studio-2010

我认为解决方案是宣布他已经做过cnnExcel,但我无法解决错误。 错误行是

cnnExcel.Open()

这是代码

Public Class Form1
Dim cnnExcel As New OleDbConnection

Public Function GetExcelSheetNames() As String()
    Dim conStr As String = ""
    Dim dt As DataTable = Nothing
    Dim opExcel As New OpenFileDialog
    opExcel.Filter = "(*.xlsx)|*.xlsx|(*.xls)|*.xls"
    opExcel.ShowDialog()
    Dim pathExcel As String = opExcel.FileName
    If pathExcel.Trim = "" Then
        MessageBox.Show("Please select file !")
        Return Nothing
    Else
        Dim Ext As String = pathExcel.Substring(pathExcel.LastIndexOf(",") + 1)
        If Ext.Length = 3 Then
            conStr = "Provider=Microsoft.jet.OLEDB.4.0;Data Source=" + pathExcel + ";Extended Properties='Excel 8.0;HDR=yes;IMEX=1';"
        ElseIf Ext.Length = 4 Then
            conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathExcel + ";Extended Properties='Excel 12.0 xml;HDR=Yes';"
        End If
        cnnExcel = New OleDbConnection(conStr)
        cnnExcel.Open()
        dt = cnnExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
        If dt Is Nothing Then
            Return Nothing
        End If
        Dim excelSheetNames As [String]() = New [String](dt.Rows.Count - 1) {}
        Dim i As Integer = 0
        For Each row As DataRow In dt.Rows
            excelSheetNames(i) = row("TABLE_NAME").ToString()
            i += 1
        Next
        cnnExcel.Close()
        Return excelSheetNames
    End If

End Function

1 个答案:

答案 0 :(得分:1)

由于您正在初始化If...ElseIf中的连接字符串,但它仍然未初始化,这意味着两个条件都不匹配,因此Ext.Length既不是= 3也不是= 4也不是pathExcel.LastIndexOf(",") pathExcel.LastIndexOf(".")。原因是您使用的是Dim extension = System.IO.Path.GetExtension(pathExcel) If extension.Equals(".xls", StringComparison.InvariantCultureIgnoreCase) Then conStr = "Provider=Microsoft.jet.OLEDB.4.0;Data Source=" + pathExcel + ";Extended Properties='Excel 8.0;HDR=yes;IMEX=1';" ElseIf extension.Equals(".xlsx", StringComparison.InvariantCultureIgnoreCase) Then conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathExcel + ";Extended Properties='Excel 12.0 xml;HDR=Yes';" Else ' should not happen with the current OpenFileDialog settings ' Throw New NotSupportedException("Illegal file-path, it must be either .xls or .xlsx") End If 而不是{{1}}。

但是,我会改用System.IO.Path.GetExtension

{{1}}