Adding Excel Sheets to End of Workbook

2019-03-02 14:46发布

I am trying to add excel worksheets to the end of a workbook, reserving the first sheet for a summary.

import win32com.client

Excel = win32com.client.DispatchEx('Excel.Application')
Book = Excel.Workbooks.Add()

Excel.Visible = True

Book.Worksheets(3).Delete()
Book.Worksheets(2).Delete()

Sheet = Book.Worksheets(1)

Sheet.Name = "Summary"

Book.Worksheets.Add(After=Sheet)

Sheet = Book.Worksheets(2)

Sheet.Name = "Data1"

This code adds the new sheet to the left, despite using After=Sheet, and when I modify the sheet named "Data1", it overwrites the sheet named "Summary".

This is similar to this problem:

Adding sheets to end of workbook in Excel (normal method not working?)

but the given solutions don't work for me.

2条回答
对你真心纯属浪费
2楼-- · 2019-03-02 15:01

Try using Sheet = excelApp.ActiveSheet:

Book.Worksheets.Add(After=Sheet)
Sheet = Book.ActiveSheet
Sheet.Name = "Data1"
查看更多
走好不送
3楼-- · 2019-03-02 15:20

Try using this by adding Before = None:

add = Book.Sheets.Add(Before = None , After = Book.Sheets(book.Sheets.count))
add.Name = "Data1"
查看更多
登录 后发表回答