简体   繁体   中英

open excel file without giving the full path in VB.Net

I have an error while trying to open two excel files with giving only their names and not the full path (error: file not exist), the files are both in the same folder as the project (Debug). I am trying to not use a static path so when i change the laptop the project will always work. This is the code that i am using. Thanks for your help

Dim xlApp As Excel.Application
    Dim xlBook As Excel.Workbook
    Dim xlSheet As Excel.Worksheet

    xlApp = New Excel.Application
    xlBook = xlApp.Workbooks.Open(Filename:="c:\EMP_.xlsx", IgnoreReadOnlyRecommended:=True, ReadOnly:=False, Editable:=True)
    xlSheet = xlBook.Worksheets(1)
    If DataGridView1.DataSource IsNot Nothing Then
        Dim i, j As Integer
        For i = 1 To DataGridView1.RowCount - 1
            For j = 1 To DataGridView1.ColumnCount
                xlSheet.Cells(i + 1, j) = DataGridView1.Rows(i - 1).Cells(j - 1).Value
            Next
        Next
        xlApp.Visible = True
        xlApp.UserControl = True
        xlApp.Quit()
        xlApp = Nothing
    Else
        MsgBox("Le tableau est vide")
    End If

Use an OpenFileDialog to show a user interface that you can choose which excel file you want to open. They're easy to use:

Dim ofd as New OpenFileDialog

Dim result = ofd.ShowDialog

If result <> DialogResult.OK Then Return 'if the user cancels

xlApp.Workbooks.Open(Filename:= ofd.Filename ...

Per Jimi's comment, something like this will read an xlsx that is alongside the exe:

Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "emp_.xlsx")
Path.Combine(Application.StartupPath, "emp_.xlsx")

Always use Path.Combine to combine paths, not string concatenation


You asked about moving the app to another PC:

  • THe new pc does NOT need Vsual Studio installed - visual studio creates a standalone EXE that will run without needing VS
  • The new PC WILL need to have an appropriate version of the .Net Framework installed. Most Windows 10 PCs will meet this requirement, but users will see a message that tells them to install it if not
  • The new PC WILL need to have Excel installed. Per my comment, if you dont want this or cannot guarantee it (paying for an office licence just to read an excel file is expensive and unnecessary) you should use the ACE driver or EPPlus to read your excel; neither needs Excel and both are free

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM