使用vb.net写入excel工作表时出错

时间:2011-02-08 18:23:36

标签: vb.net excel .net-2.0

当我尝试使用VB.net 2005写入excel工作表时收到错误消息

  

操作必须使用可更新的查询

我已经通过S / O搜索结果了 https://stackoverflow.com/search?q=Operation+must+use+an+updateable+query
但没有回应解决我的问题。

我的代码是:

Dim strXLScn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & xlsFilePath.Text & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"""

        Dim XLConn As New OleDb.OleDbConnection(strXLSconn)
        Dim XLcmd As New System.Data.OleDb.OleDbCommand
        Dim sSQLWriteToExcel As String

        strExcel = "INSERT INTO [Sheet1$A1:A1] Values ('" & sCity & "')"

        Dim oleCMD As New OleDb.OleDbCommand(strExcel, XLConn)
        Dim oleDA As New OleDb.OleDbDataAdapter(oleCMD)

        XLConn.Open()
        XLcmd.Connection = XLConn

        XLcmd.CommandText = strExcel
        XLcmd.ExecuteNonQuery()
        XLConn.Close()

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

首先,确保你有Option Explicit ON,这将有助于你尝试使用你从未声明过的变量。其次,从连接字符串的末尾删除IMEX = 1。第三,确保您的Excel文档有标题行。这段代码对我有用:

     Dim strXLScn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""C:\Temp\test.xls"";Extended Properties=""Excel 8.0;HDR=Yes"""

    Dim XLConn As New OleDb.OleDbConnection(strXLScn)
    Dim XLcmd As New System.Data.OleDb.OleDbCommand
    Dim strExcel As String
    Dim sCity As String = "Sydney"
    strExcel = "INSERT INTO [Sheet1$] Values ('" & sCity & "')"

    Dim oleCMD As New OleDb.OleDbCommand(strExcel, XLConn)
    Dim oleDA As New OleDb.OleDbDataAdapter(oleCMD)

    XLConn.Open()
    XLcmd.Connection = XLConn

    XLcmd.CommandText = strExcel
    XLcmd.ExecuteNonQuery()
    XLConn.Close()

答案 1 :(得分:0)

(Appoligies这不是在VB中,而是在C#中。但我认为它很简单且足够短,应该能够轻松转换为VB。)

我发现这篇文章和其他几篇文章一样有用。这就是我想出来的。它适用于VS2010。

请注意Excel工作表有标题。因此,连接字符串中的“HDR = Yes”。

以下是我如何在C#中格式化字符串。它使用String变量(代理)和结构(地址):

“INSERT INTO [代理机构名单$]([机构],[街道1],[街道2],[城市],[邮政编码],[国家代码])价值观('”+代理商+“',' “+ Address.Street1.Replace(”'“,”''“)+”','“+ Address.Street2.Replace(”'“,”''“)+”','“+ Address.City。替换(“'”,“''”)+“','”+ Address.PostalCode.Replace(“'”,“''”)+“','”+ Address.Country.Replace(“'”, “''”)+“')”

请注意,工作表被调出(“代理商列表”),每个字段/标题(例如“[Agency]”)都被括起来,String.Replace方法用于处理嵌入式单引号(tick)标记

干杯!

public void InsertExcelData(String fileName, String sqlString)
{
    string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;\";";

    OleDbConnection connection = new OleDbConnection(connectionString);

    OleDbCommand command = new OleDbCommand(connectionString, connection);

    command.CommandText = sqlString;

    // Connect to the worksheet
    connection.Open();

    // Do the Insert
    command.ExecuteNonQuery();

    // Clean up
    connection.Close();
    connection.Dispose();
}