将 Sheet 添加到 Excel 工作簿

Adding a Sheet to an Excel Workbook

我正在尝试在 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 打开我正在查询。

据我所知,您的代码给出的错误是:

A first chance exception of type '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 张工作表。

Note that ws will be the last sheet in the Workbook. In my example this would be 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"

Note that ws1 references to the first sheet. As said above a Workbook by default comes with one sheet.