从数据文本框到 excel vb.net
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26298848/
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
from data textbox to excel vb.net
提问by pollonz
I have this code that allows me to export the data contained in the two TextBoxsin an excel spreadsheet, the problem is that the excel file is not created. I put the two statements are not working for rescuing comment below, maybe someone can test it and tell me why it is wrong.
我有这段代码可以让我TextBoxs在excel电子表格中导出两者中包含的数据,问题是没有创建excel文件。我把这两个陈述都不适用于下面的拯救评论,也许有人可以测试一下并告诉我为什么它是错误的。
Dim objExcel As New Excel.Application ' Represents an instance of Excel
Dim objWorkbook As Excel.Workbook 'Represents a workbook object
Dim objWorksheet As Excel.Worksheet 'Represents a worksheet object
objWorkbook = objExcel.Workbooks.Add
objWorksheet = CType(objWorkbook.Worksheets.Item(1), Excel.Worksheet)
'This form contains two text boxes, write values to cells A1 and A2
objWorksheet.Cells(1, 1) = TextBox1.Text
objWorksheet.Cells(2, 1) = TextBox2.Text
objWorkbook.Close(False)
'objWorkbook.Save()
'or
'objWorkbook.SaveAs("C:\Temp\Book1.xls")
objExcel.Quit()
回答by ???ěxě?
Code is tried and tested
代码经过尝试和测试
Your issue can be from a few different things that I can see. I provided a few issues that I could see from your code you posted.
你的问题可能来自我可以看到的一些不同的事情。我提供了一些可以从您发布的代码中看到的问题。
- Your calling .Close before actually saving the workbook.
- You didn't specify the "FileFormat" in the save function.
- Your not quitting the instance of Excel.
- It's importantto release ALLobjects of Excel you use. If not, it's being held up in memory and will not be released.
- 在实际保存工作簿之前调用 .Close。
- 您没有在保存功能中指定“文件格式”。
- 您没有退出 Excel 实例。
- 这是重要的,以释放所有您使用的Excel对象。如果没有,它会被保留在内存中并且不会被释放。
Code Below
下面的代码
Dim xlApp As New excel.Application
Dim xlWorkBook As excel.Workbook
Dim xlWorkSheet As excel.Worksheet
Try
xlApp.DisplayAlerts = False
xlWorkBook = xlApp.Workbooks.Add
xlWorkSheet = DirectCast(xlWorkBook.Sheets("Sheet1"), excel.Worksheet)
xlApp.Visible = False 'Don't show Excel; we can and we don't have too
xlWorkSheet.Cells(1, 1) = TextBox1.Text
xlWorkSheet.Cells(2, 1) = TextBox2.Text
xlWorkBook.SaveAs("C:\Temp\Book1.xls", FileFormat:=56) 'Save the workbook
xlWorkBook.Close() 'Close workbook
xlApp.Quit() 'Quit the application
'Release all of our excel objects we used...
ReleaseObject(xlWorkSheet)
ReleaseObject(xlWorkBook)
ReleaseObject(xlApp)
Catch ex As Exception
End Try
Method to Release Excel Objects
释放Excel对象的方法
Public Shared Sub ReleaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub

