vb.net 使用 VB2010 创建 Excel 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27406410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating Excel Files using VB2010
提问by HumanlyRespectable
I have a form with 1 button to create an Excel file on my desktop.
我有一个带有 1 个按钮的表单,可以在我的桌面上创建一个 Excel 文件。
I get error message:
我收到错误消息:
NullReferenceException Was Unhandled
Object reference not set to an instance of an object
NullReferenceException 未处理
对象引用未设置为对象的实例
and it highlights the code:
它突出显示了代码:
WB = excelapp.workbooks.add
I did add the reference "Microsoft excel 14.0" and my full code is below:
我确实添加了参考“Microsoft excel 14.0”,我的完整代码如下:
imports excel = microsoft.office.interop.excel
dim excelapp as excel.application
dim WB as excel.workbook
sub button1()
WB = excelapp.workbooks.add
excelapp.visible=true
end sub
回答by Keith
Missing New on your Excel instance for starters:
对于初学者来说,您的 Excel 实例上缺少 New:
Dim xlApp As New Excel.Application
Dim xlWorkbook As Excel.Workbook = xlApp.Workbooks.Add()
Dim xlWorksheet As Excel.Worksheet = CType(xlWorkbook.Sheets("sheet1"), Excel.Worksheet)
xlWorksheet.Cells(1, 1) = "data in first cell"
xlWorksheet.SaveAs(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\" & "Test.xlsx")
xlWorkbook.Close()
xlApp.Quit()
xlApp = Nothing
xlWorkBook = Nothing
xlWorkSheet = Nothing
You should probably put this in Try/Catch/Finally block to catch errors in case you run into issues, but mostly because if the program doesn't continue properly finish that code block, an EXCEL.EXE will remain open in your task manager, as well as whatever Excel file it was accessing will be "in use by another program" when you try to access/modify/delete it.
您可能应该将它放在 Try/Catch/Finally 块中以在遇到问题时捕获错误,但主要是因为如果程序没有继续正确完成该代码块,EXCEL.EXE 将在您的任务管理器中保持打开状态,以及当您尝试访问/修改/删除它时,它正在访问的任何 Excel 文件都将“被另一个程序使用”。
回答by Hüseyin Sekmeno?lu
just add one line, then it'll work
只需添加一行,然后它就会起作用
imports excel = microsoft.office.interop.excel
dim excelapp as excel.application
dim WB as excel.workbook
sub button1()
excelapp = new excel.application
WB = excelapp.workbooks.add
excelapp.visible=true
end sub

