从VB导出到Excel时的Interop问题

时间:2014-08-19 20:12:56

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

我正在尝试使用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()

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

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

尝试将Debug打印添加到您读取列的代码中,看看是否提出了一些可能需要注意的奇怪数据类型。逐步执行下一个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

好的代码BTW。如果您从其他作者那里复制它,那么发布他们的URL以获得信用将是一件好事。