在VS 2012上我创建了一个VB.NET计算应用程序(基于变量输入的输出),我需要保存这些输入和输出。将数据输出到Excel工作表中的某些单元格, 这是我使用的代码示例:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim xls As Microsoft.Office.Interop.Excel.Application
Dim xlsWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlsWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
xls = New Microsoft.Office.Interop.Excel.Application
xlsWorkBook = xls.Workbooks.Open("D:\bookl.xlsx")
xlsWorkSheet = xlsWorkBook.Sheets("sheet1")
xlsWorkSheet.Cells(1, 1) = TextBox1.Text
xlsWorkBook.Close()
xls.Quit()
End Sub
我的问题是,每次我点击保存按钮时,它都会将数据保存到excel表文件中,我必须先指定其路径。
我想做的是,如果有任何方法从VB加载它自己然后选择保存它的位置(因为我将在很多机器中使用它,所以我不想把excel文件每次我在任何其他机器上使用该应用程序时,在相同的路径中)
答案 0 :(得分:4)
从My.Resources位置打开Excel文件
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim xlsWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlsWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim xls As New Microsoft.Office.Interop.Excel.Application
Dim resourcesFolder = IO.Path.GetFullPath(Application.StartupPath & "\..\..\Resources\")
Dim fileName = "book1.xlsx"
xlsWorkBook = xls.Workbooks.Open(resourcesFolder & fileName)
xlsWorkSheet = xlsWorkBook.Sheets("Sheet1")
xlsWorkSheet.Cells(1, 1) = TextBox1.Text
xlsWorkBook.Close()
xls.Quit()
MsgBox("file saved to " & resourcesFolder)
End Sub
必须将资源模板xlsx文件复制到输出目录,因此请编辑其属性并选择(实际上我不确定您是否需要此...)
Build Action = Content
Copy To Output Directory = Copy Always
<强> P.S。这只是与当前代码一起使用的示例,但如果您要创建/保存/修改Excel文件,我强烈建议您使用EPPlus Library。
答案 1 :(得分:0)
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim xlsWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlsWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim xls As New Microsoft.Office.Interop.Excel.Application
Dim resourcesFolder = IO.Path.GetFullPath(Application.StartupPath & "\..\..\Resources\")
Dim fileName = "book1.xlsx"
xlsWorkBook = xls.Workbooks.Open(resourcesFolder & fileName)
xlsWorkSheet = xlsWorkBook.Sheets("Sheet1")
xlsWorkSheet.Cells(1, 1) = TextBox1.Text
xlsWorkBook.Close()
xls.Quit()
MsgBox("file saved to " & resourcesFolder)
End Sub