2013-10-24 66 views
0

我正在上傳一個Excel工作表,並希望將其數據移動到數據庫中的另一個表。最近兩天我得到一個錯誤(System.Data.OleDb.OleDbException invalid argument),但是,如果我設計一個非常簡單的應用程序,它工作正常。請幫我System.Data.OleDb.OleDbException無效的參數

 
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("TERAMSConnectionString").ConnectionString) 
      Dim path As String = FileUpload1.PostedFile.FileName 
      Dim excelConnectionString As String = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + (path + ";Extended Properties=Excel 12.0;Persist Security Info=False")) 
      Dim excelConnection As OleDbConnection = New OleDbConnection(excelConnectionString) 
      conn.Open() 
      excelConnection.Open() 
      Dim cmd As OleDbCommand = New OleDbCommand("Select * from [Sheet1$]", excelConnection) 
      'Clears any previous data 
      Dim sClearSQL = "DELETE FROM Desktop_Compare " 
      Dim SqlCmd As SqlCommand = New SqlCommand(sClearSQL, conn) 
      SqlCmd.ExecuteNonQuery() 
      Dim dReader As OleDbDataReader = cmd.ExecuteReader 
      Dim sqlBulk As SqlBulkCopy = New SqlBulkCopy(conn) 
      excelConnection.Close() 
      conn.Close() 
     End Using 


Line 74:    Dim excelConnection As OleDbConnection = New OleDbConnection(excelConnectionString) 
Line 75:    conn.Open() 
Line 76:    **excelConnection.Open()** 
Line 77:    Dim cmd As OleDbCommand = New OleDbCommand("Select * from [Sheet1$]", excelConnection) 
Line 78:    'Clears any previous data 
+0

您在哪一點得到異常?作爲一個便箋,我會推薦使用'&'來連接字符串而不是'+'(我看到+導致一些奇怪的問題,因爲它試圖將字符串「添加」到一起而不是連接它們) – Grahamvs

+0

@Grahamvs好的,我得到錯誤在「excelConnection.Open()」告訴用戶代碼是未處理的。 – Miank

回答

0

試着改變你的連接字符串:

Dim excelConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & path & ";" 

如果還是不行,請嘗試更改/添加Extended PropertiesPersist Security Info一次一個,因爲它似乎無論你是對ACE驅動程序有問題,或者其中一個附加參數導致問題

至於您的用戶得到未處理的錯誤,您可以嘗試如下所示:

 Dim excelConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & path & ";" 

     Using excelConnection As OleDb.OleDbConnection = New OleDb.OleDbConnection(excelConnectionString) 
      Try 
       excelConnection.Open() 

       Using cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("Select * from [Sheet1$]", excelConnection) 

        'Clears any previous data 
        Dim sClearSQL As String = "DELETE FROM Desktop_Compare " 
        Using SqlCmd As SqlClient.SqlCommand = New SqlClient.SqlCommand(sClearSQL, conn) 
         SqlCmd.ExecuteNonQuery() 
        End Using 

        Dim dReader As OleDb.OleDbDataReader = cmd.ExecuteReader 
        Dim sqlBulk As SqlClient.SqlBulkCopy = New SqlClient.SqlBulkCopy(conn) 
        excelConnection.Close() 

       End Using 

      Catch ex As Exception 
       ' Handle errors here 

      Finally 
       If Not excelConnection.State = ConnectionState.Closed Then 
        Try 
         excelConnection.Close() 
        Catch ex As Exception 
        End Try 
       End If 

      End Try 

     End Using