【发布时间】:2020-03-29 17:13:10
【问题描述】:
我在尝试打开两个仅提供名称而不是完整路径的 Excel 文件时出错(错误:文件不存在),这些文件都与项目位于同一文件夹中(调试)。 我试图不使用静态路径,所以当我更换笔记本电脑时,项目将始终有效。 这是我正在使用的代码。 感谢您的帮助
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
【问题讨论】:
-
为什么不用可执行当前路径?作为
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)或AppDomain.CurrentDomain.BaseDirectory。如果是 WinForms 应用程序,您还可以使用Application.StartupPath等。或者将文件复制到专用于这些操作的路径之一,如Application.LocalUserAppDataPath、Application.UserAppDataPath和Application.CommonAppDataPath,当然也可以使用Path.Combine来构建最终路径 -
我使用了 Application.StartupPath 和 \MyFileName.xlsx 并且可以正常工作,谢谢
-
不要使用 Excel 自动化来读取 Excel 文件,以便在 datagridview 中显示它。 use the ACE database driver 连接到 XLSX 文件并将数据从中提取到数据表中(然后您使用
datagridview1.DataSource = datatable绑定到 datagridview)或 use EPPlus -
我实际上是在使用 xlsx 文件从 Datagridview 导出显示的数据,ACE 数据库驱动程序对我有用吗?
标签: excel vb.net visual-studio