我使用下面的互操作代码,我使用" 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
答案 0 :(得分:2)
如果将excel.Worksheets.Add()
的结果设置为变量(即Dim WS as Worksheet = excel.Worksheets.Add()
),则应该能够直接为该变量的name
属性分配新值。
将给定代码作为框架......
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