将工作表添加到Excel工作簿

时间:2017-02-03 15:03:27

标签: excel vb.net excel-interop

我试图在Excel中创建一个包含多个工作表的Workbook,但我无法弄清楚如何创建多个工作表。我可以创建一个很好,但当我尝试创建第二个写入时,我得到一个错误。

Dim app As Application = New Application
Dim xlApp As New Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim newXlApp As Excel.Application = New Microsoft.Office.Interop.Excel.Application
Dim newXlWorkbook As Excel.Workbook
Dim newXlSheet As Excel.Worksheet
Dim newXlSheet2 As Excel.Worksheet

Public Sub createWorkBook()
    newXlWorkbook = newXlApp.Workbooks.Add()

    newXlSheet = newXlWorkbook.Sheets("Sheet1")
    newXlSheet2 = newXlWorkbook.Sheets.Add("Sheet2")

    newXlSheet.Cells(1, 1) = "Task ID"
    newXlSheet.Cells(1, 2) = "Collective Tasks"
    newXlSheet.Cells(1, 3) = "Supported Task"

    newXlSheet2.Cells(1, 1) = "Parent Collective Task"
    newXlSheet2.Cells(1, 2) = "Individual Task"
End Sub

我不确定它是否重要,但我还有一个单独的Excel Workbook打开,我正在查询。

1 个答案:

答案 0 :(得分:4)

从我看到的代码所给出的错误将是:

  

类型' System.Runtime.InteropServices.COMException'

的第一次机会异常

如果您要向Excel Workbook添加多个表格,则可以使用以下代码:

Dim app As New Excel.Application
Dim wb As Excel.Workbook = app.Workbooks.Add()
Dim ws As Excel.Worksheet

ws = CType(wb.Sheets.Add(Count:=10), Excel.Worksheet)

默认情况下,Workbook附带一个Sheet。如果要添加多个设置Count:= parameter。正如您在我的示例中所看到的,我使用了 10 。这将留下11张表格可供使用。

  

请注意,ws将是Workbook中的最后一张。在我的示例中,这将是 Sheet11

如果您想使用每个Worksheet,那么您需要查看以下代码:

Dim ws1 As Excel.Worksheet = CType(wb.Sheets(1), Excel.Worksheet)
Dim ws2 As Excel.Worksheet = CType(wb.Sheets.Add(), Excel.Worksheet)

ws1.Cells(1, 1) = "Task ID"
ws1.Cells(1, 2) = "Collective Tasks"
ws1.Cells(1, 3) = "Supported Task"

ws2.Cells(1, 1) = "Parent Collective Task"
ws2.Cells(1, 2) = "Individual Task"
  

请注意ws1对第一张表的引用。如上所述,默认情况下Workbook附带一张表。