【问题标题】:ExecuteNonQuery - Data Type Mismatch in Criteria Expression when adding data (VB.Net and Excel 2010)ExecuteNonQuery - 添加数据时条件表达式中的数据类型不匹配(VB.Net 和 Excel 2010)
【发布时间】:2014-09-25 06:53:47
【问题描述】:

大家好。我在 vb.net 中编写了一些代码,以使用表单将行添加到 Excel 文件 (xls) 中。表单中有两个文本框。 excel 文件中的两列被格式化为文本。如果我在文本框中输入任何数字,一切正常。如果我输入数字和字符或仅输入字符,则会在 ExecuteNonQuery 上收到“条件表达式中的数据类型不匹配”错误。我已经尝试了许多不同的方法来解决它,但没有任何积极的结果。我需要修复它,因为我将添加一些其他文本框来输入文本(文本和数字,而不仅仅是数字)。请问有人可以帮助我吗?这是我的代码。提前感谢您的任何建议。

    Public Class Edit1

    Public con As New OleDb.OleDbConnection
    Public dbProvider As String
    Public dbSource As String
    Public ds As New DataSet
    Public da As OleDb.OleDbDataAdapter
    Public sql As String

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        dbProvider = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;"
        dbSource = "Data Source = c:\test1.xls"
        con.ConnectionString = dbProvider & dbSource
        con.Open()
        sql = "SELECT * FROM [dbdata$]"
        da = New OleDb.OleDbDataAdapter(sql, con)
        da.Fill(ds, "table1")
        con.Close()
    End Sub

    Private Sub Button6_Click(sender As System.Object, e As System.EventArgs) Handles Button6.Click

        Dim cmd As New OleDbCommand
        Dim str1 As String
        Dim str2 As String
        cmd.CommandType = CommandType.Text
        str1 = TextBox1.Text
        str2 = TextBox2.Text
        cmd.CommandText = "INSERT INTO [dbdata$] (item1,item2) VALUES (str1,str2);"
        cmd.Parameters.AddWithValue("@item1", str1)
        cmd.Parameters.AddWithValue("@item2", str2)
        'cmd.Parameters.Add("@item1", TextBox1.Text) 'this generate the same ExecuteNonQuery mismatch error
        'cmd.Parameters.Add("@item2", TextBox2.Text) 'this generate the same ExecuteNonQuery mismatch error
        'cmd.Parameters("@item1").Value = TextBox1.Text 'this generate the same ExecuteNonQuery mismatch error
        'cmd.Parameters("@item2").Value = TextBox2.Text 'this generate the same ExecuteNonQuery mismatch error
        cmd.Connection = con
        con.Open()
        cmd.ExecuteNonQuery()
        con.Close()


    End Sub
End Class

更新 - 好的,伙计们,我已经解决了这个问题。我所做的是清理 Excel 工作表,删除所有格式化和填充的单元格,只留下第一行的列名。现在它可以工作了,但还有一个小问题。看起来ExecuteNonQuery 检查最后填充的单元格以识别要在下一个要填充的单元格中使用的单元格格式。因此,由于第一行将“item1”和“item2”(不带引号)作为列名,因此代码在第 1 列上用单引号写入数字(即,如果文本框为 23,则单元格中将为 @ 987654324@.

但是,如果我手动编写至少一个数字(在第二行),那么代码就可以正常工作。无论我在文本框中写入什么类型的数据,有什么想法可以避免这种行为以便在单元格中写入?提前感谢您的帮助。

【问题讨论】:

    标签: vb.net excel executenonquery


    【解决方案1】:

    我最近遇到了类似的问题。它最终成为单元格的格式。即使我更改了整个列设置,我仍然会遇到类型不匹配。我让它最终工作的唯一方法是将所有内容复制到工作簿中的另一张工作表中,并将所有内容格式化为文本。然后我删除了第一张表并将新表重命名为旧名称。之后效果很好。

    否则,只需在旧列旁边插入新列,将其格式化为文本,然后复制和 PASTE_SPECIAL,然后仅选择值。这将消除每个单元格左上角的箭头。

    这两种修复都适用于我的添加、搜索、更新等。

    希望这会有所帮助,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多