【问题标题】:Interop issue when exporting to Excel from VB从 VB 导出到 Excel 时的互操作问题
【发布时间】:2014-08-19 20:12:55
【问题描述】:

我正在尝试使用 Excel Interop 将 VB.net 数据表保存到 Excel。

使用下面的代码,我得到错误“方法的类型签名不兼容互操作”

Imports System.Data.SqlClient
Imports System.Data
Imports System.IO.Directory
Imports Microsoft.Office.Interop.Excel 
Imports Microsoft.Office.Interop

Public Class ViewBillForm

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        'Initialize the objects before use
        Dim dataAdapter As New SqlClient.SqlDataAdapter()
        Dim dataSet As New DataSet
        Dim command As New SqlClient.SqlCommand
        Dim datatableMain As New System.Data.DataTable()
        Dim connection As New SqlClient.SqlConnection

        'Assign your connection string to connection object
        connection.ConnectionString = "server=inlt01\SQLEXPRESS; database=DaisyBilling; integrated security=yes"
        command.Connection = connection
        command.CommandType = CommandType.Text
        'You can use any command select
        command.CommandText = "Select * from [dbo].[" + DaisyBillingForm.TextBox1.Text + "]"
        dataAdapter.SelectCommand = command

        Dim f As FolderBrowserDialog = New FolderBrowserDialog
        Try
            If f.ShowDialog() = DialogResult.OK Then
                'This section help you if your language is not English.
                System.Threading.Thread.CurrentThread.CurrentCulture = _
                System.Globalization.CultureInfo.CreateSpecificCulture("en-US")
                Dim oExcel As Excel.Application
                Dim oBook As Excel.Workbook
                Dim oSheet As Excel.Worksheet
                oExcel = CreateObject("Excel.Application")
                oBook = oExcel.Workbooks.Add(Type.Missing)
                oSheet = oBook.Worksheets(1)

                Dim dc As System.Data.DataColumn
                Dim dr As System.Data.DataRow
                Dim colIndex As Integer = 0
                Dim rowIndex As Integer = 0

                'Fill data to datatable
                connection.Open()
                dataAdapter.Fill(datatableMain)
                connection.Close()

                'Export the Columns to excel file
                For Each dc In datatableMain.Columns
                    colIndex = colIndex + 1
                    oSheet.Cells(1, colIndex) = dc.ColumnName
                Next

                'Export the rows to excel file
                For Each dr In datatableMain.Rows
                    rowIndex = rowIndex + 1
                    colIndex = 0
                    For Each dc In datatableMain.Columns
                        colIndex = colIndex + 1
                        oSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)

                    Next
                Next

                'Set final path
                Dim fileName As String = "\ExportedAuthors" + ".xls"
                Dim finalPath = f.SelectedPath + fileName
                Textbox1.Text = finalPath
                oSheet.Columns.AutoFit()
                'Save file in final path
                oBook.SaveAs(finalPath, XlFileFormat.xlWorkbookNormal, Type.Missing, _
                Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, _
                Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)

                'Release the objects
                ReleaseObject(oSheet)
                oBook.Close(False, Type.Missing, Type.Missing)
                ReleaseObject(oBook)
                oExcel.Quit()
                ReleaseObject(oExcel)
                'Some time Office application does not quit after automation: 
                'so i am calling GC.Collect method.
                GC.Collect()

                MessageBox.Show("Export done successfully!")

            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK)
        End Try
    End Sub

    Private Sub ReleaseObject(ByVal o As Object)
        Try
            While (System.Runtime.InteropServices.Marshal.ReleaseComObject(o) > 0)
            End While
        Catch
        Finally
            o = Nothing
        End Try

    End Sub
End Class

我已经进行了一些谷歌搜索,建议的解决方法是将值作为字符串传递,但是当我将 .ToString() 添加到以下行时,它会在我尝试导出时挂起。

oSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName).ToString()

非常感谢任何帮助。

【问题讨论】:

  • 更新:我昨晚去关闭我的电脑,它问我是否要“保存”Book8.xls。这很奇怪,因为 Excel 似乎没有在桌面上打开。我保存了文件,当我打开文件时果然显示了导出的数据。所以问题似乎是由于某种原因Excel没有在前台打开并且保存功能没有正常工作

标签: vb.net office-interop export-to-excel


【解决方案1】:

代码对我来说工作正常。我使用了一个真正的 SQL Server 和一个简单的表。

尝试在读取列的代码中添加调试打印,看看是否提出了一些可能需要注意的奇怪数据类型。单步执行下一个 For 循环,看看错误发生在哪里。

            'Export the Columns to excel file
            For Each dc In datatableMain.Columns
                colIndex = colIndex + 1
                oSheet.Cells(1, colIndex) = dc.ColumnName
                Debug.Print(dc.ColumnName & ": " & dc.DataType.Name)
            Next
            Stop ' or breakpoint

不错的代码顺便说一句。如果您从其他作者那里复制了它,最好发布他们的 URL 以获得信用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 2011-11-02
    相关资源
    最近更新 更多