[英]Adding a Sheet to an Excel Workbook
I'm trying to create a Workbook
with multiple sheets in Excel but I can't figure out how to create the multiple sheets. 我正在尝试在Excel中创建具有多个
Workbook
表的Workbook
,但我不知道如何创建多个工作表。 I can create one just fine, but when I try to create a second one to write to I get an error. 我可以创建一个就好了,但是当我尝试创建第二个要写的文件时却出现了错误。
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
I'm not sure if it matters or not, but I also have a separate Excel Workbook
open that I'm querying. 我不确定是否重要,但是我还要打开一个单独的Excel
Workbook
。
From what I can see the error your code is giving will be: 从我可以看到您的代码给出的错误将是:
A first chance exception of type 'System.Runtime.InteropServices.COMException'
类型为“ System.Runtime.InteropServices.COMException”的第一次机会异常
If you want to add multiple Sheets to your Excel Workbook
this is the code to do that: 如果要将多个工作表添加到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)
By default a Workbook
comes with one Sheet
. 默认情况下,
Workbook
随附一张Workbook
Sheet
。 If you want to add more than one set the Count:= parameter
. 如果要添加多个,请设置
Count:= parameter
。 As you can see in my example I have used 10 . 如您在我的示例中看到的,我使用了10 。 This will leave me with 11 Sheets to work with.
这将给我留下11张纸供您使用。
Note that
ws
will be the last sheet in theWorkbook
.请注意,
ws
将是Workbook
的最后一张纸。 In my example this would be Sheet11 .在我的示例中,这将是Sheet11 。
If you want to work with each Worksheet
then you would need to look at the following code: 如果要使用每个
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.请注意,
ws1
引用了第一张纸。 As said above aWorkbook
by default comes with one sheet.如上所述,默认情况下,
Workbook
随附一张纸。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.