declare/open excel file in vb.net

你离开我真会死。 提交于 2020-01-03 02:59:09

问题


I've been trying for a while to declare or to open a excel sheet in vb.net. I already read excel file in vb.net and other links but it doesn't work.

I added Microsoft Excel 12.0 Object Library. I included:

Imports Microsoft.VisualBasic
Imports System.Net.Mime.MediaTypeNames
Imports Microsoft.Office.Interop 

I want to declare / open the excel file in a module:

Public Module postleitzahlen_array

Dim myarray As String

Dim xlApp As Excel.Application
xlApp = New Excel.ApplicationClass ' here is the error, XlApp "has to be declared"

Can someone help me?

EDIT:

Okay, i noticed that i use excel 2007, and there is a difference - now I'm using follwing code from http://vb.net-informations.com/excel-2007/vb.net_excel_2007_create_file.htm

Sub test()
        Dim xlApp As Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkSheet As Excel.Worksheet

        Dim misValue As Object = System.Reflection.Missing.Value

        xlApp = New Excel.ApplicationClass
        xlWorkBook = xlApp.Workbooks.Add(misValue)
        xlWorkSheet = xlWorkBook.Sheets("sheet1")
        xlWorkSheet.Cells(1, 1) = "http://vb.net-informations.com"
        xlWorkSheet.SaveAs("D:\vbexcel.xlsx")

        xlWorkBook.Close()
        xlApp.Quit()

        releaseObject(xlApp)
        releaseObject(xlWorkBook)
        releaseObject(xlWorkSheet)

        MsgBox("Excel file created , you can find the file c:\")
    End Sub


    Private Sub releaseObject(ByVal obj As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            obj = Nothing
        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
        End Try
    End Sub

but I get an error in xlWorkSheet = xlWorkBook.Sheets("sheet1") saying "(Exception by HRESULT: 0x8002000B (DISP_E_BADINDEX))

Edit2: I use a german excel, so "sheet1" throws an error --> "tabelle1" is the right word :)


回答1:


This helped me get started, although for C#. I suspect the concepts are similar for VB.




回答2:


As for your error, substituting ApplicationClass to simply Application had solved my problem.



来源:https://stackoverflow.com/questions/7173167/declare-open-excel-file-in-vb-net

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