问题
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.
回答1:
Try using this by adding Before = None
:
add = Book.Sheets.Add(Before = None , After = Book.Sheets(book.Sheets.count))
add.Name = "Data1"
回答2:
Try using Sheet = excelApp.ActiveSheet
:
Book.Worksheets.Add(After=Sheet)
Sheet = Book.ActiveSheet
Sheet.Name = "Data1"
来源:https://stackoverflow.com/questions/40179804/adding-excel-sheets-to-end-of-workbook