使用 Interop 重命名 Excel 工作表 VB.net
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25157787/
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
Rename excel worksheet VB.net with Interop
提问by Satish
I have the below interop code where I use "excel.Worksheets.Add()" to create my sheet in already available excel book (this becomes my active sheet automatically). During this excel assigns a default name automatically. Please let me know every time I add a sheet using "excel.Worksheets.add() I should rename it to a meaningful name.
我有下面的互操作代码,我使用“excel.Worksheets.Add()”在已经可用的 Excel 工作簿中创建我的工作表(这会自动成为我的活动工作表)。在此 excel 自动分配一个默认名称。每次我使用“excel.Worksheets.add() 添加工作表时,请让我知道我应该将其重命名为有意义的名称。
Dim excel As Microsoft.Office.Interop.Excel.Application
Try
excel = New Microsoft.Office.Interop.Excel.Application
excel.Workbooks.Open("C:\Satish\TestExcel\vbexcel.xlsx")
Dim i As Integer, j As Integer
Dim diff As Integer = 1
' if you want column header from dgv elese omit the block
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
excel.Worksheets.Add()
For j = 0 To DataGridView4.ColumnCount - 1
excel.ActiveSheet.cells(1, j + 1) = DataGridView1.Columns(j).Name
Next
diff += 1
回答by Psychemaster
If you set the result of excel.Worksheets.Add()to a variable (ie. Dim WS as Worksheet = excel.Worksheets.Add()), you should then be able to directly assign a new value to that variable's nameproperty.
如果您将 的结果设置excel.Worksheets.Add()为变量(即Dim WS as Worksheet = excel.Worksheets.Add()),那么您应该能够直接为该变量的name属性分配一个新值。
Taking the given code as a framework...
将给定的代码作为框架......
Dim excel As Microsoft.Office.Interop.Excel.Application
Try
excel = New Microsoft.Office.Interop.Excel.Application
excel.Workbooks.Open("C:\Satish\TestExcel\vbexcel.xlsx")
Dim i As Integer, j As Integer
Dim diff As Integer = 1
' if you want column header from dgv elese omit the block
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim WS as Microsoft.Office.Interop.Excel.Worksheet = excel.Worksheets.Add()
WS.Name = "Enter the name here"
For j = 0 To DataGridView4.ColumnCount - 1
excel.ActiveSheet.cells(1, j + 1) = DataGridView1.Columns(j).Name
Next
diff += 1

