Excel worksheet in Windows form application without opening Excel application

大憨熊 提交于 2019-12-03 21:33:58

You probably need to instantinate your object correctly. Worksheet requires Excel COM object, so you normally instantinate its first and then access a sheet. Here is some sample code:

Dim xl As Microsoft.Office.Interop.Excel.Application
xl = New Microsoft.Office.Interop.Excel.Application
Dim wb As Microsoft.Office.Interop.Excel.Workbook
wb = xl.Workbooks.Add()
Dim ws As Microsoft.Office.Interop.Excel.Worksheet
ws = wb.ActiveSheet

Now you can work with your ws. Notice, that I do not instantinate it using Dim .. as New.

By doing this you will get an invisible instance of Excel running in your background. You must close your application explicitly after you are done to prevent it from staying in memory:

/// after your are finished
xl.Quit()
Marshal.ReleaseComObject(xl)

This is especially important if you using it in a kind of loop.

maybe you've already solved this issue, but here is my solution, i used what you posted and what i've found from another article, so i can tell you this works fine, here is my example:

    Dim xlApp As New Microsoft.Office.Interop.Excel.Application

    Dim oldCI As System.Globalization.CultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture
    System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US")
    xlApp.Workbooks.Add()
    xlApp.ActiveSheet.Delete()
    xlApp.ActiveSheet.Delete()

    With xlApp
        With .ActiveSheet.QueryTables.Add("ODBC;DRIVER=SQL Server;SERVER=" & DAO.GetNombreServidor & ";UID=" & DAO.GetLoginUsuario & ";PWD=" & DAO.GetPassUsuario & ";WSID=RICARDO2;DATABASE=" & DAO.GetNombreBaseDeDatos & "", xlApp.Range("A1"))
            .CommandText = "SELECT * FROM ESTADOS"
            .FieldNames = True
            .RowNumbers = False
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = False
            .BackgroundQuery = True
            '.RefreshStyle = xlOverwriteCells
            'xlInsertDeleteCells
            .SavePassword = False
            .SaveData = False
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .PreserveColumnInfo = False
            .Refresh(False)
        End With
    End With

    System.Threading.Thread.CurrentThread.CurrentCulture = oldCI

    xlApp.Visible = True

I hope it helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!