问题
With xlwings, I am trying to move a worksheet within a workbook to the end. For example, a workbook contains a collection of the following sheets:Sheet1, Sheet2, Sheet3
How can I move Sheet1 after Sheet3 in order to get the following order? Sheet2, Sheet3, Sheet1
If I use ws1.api.Move(Before=ws3.api)
the line works as expected, but I am not interested in the Before
parameter, I would would like to use the After
parameter. If I change the parameter from Before
to After
the worksheet moves to a new workbook, which is not what I expect, see example code:
import xlwings as xw
wb = xw.Book("test.xlsx")
ws1 = wb.sheets['Sheet1']
ws3 = wb.sheets['Sheet3']
ws1.api.Move(After=ws3.api)
By the way, the same problem occurs when I try to copy the worksheet after another, for example, ws1.api.Copy(After=ws3.api)
. What is wrong with the parameter After?
回答1:
I found the solution myself, this question is already answered here. You have to add None
before the After
parameter:
import xlwings as xw
wb = xw.Book("test.xlsx")
ws1 = wb.sheets['Sheet1']
ws3 = wb.sheets['Sheet3']
ws1.api.Move(None, After=ws3.api)
Strictly speaking, the question seems to be more related to pywin32 than to xlwings, because apparently .api
accesses the underlying pywin32 objects, as described here
来源:https://stackoverflow.com/questions/64820928/move-worksheet-within-a-workbook-to-the-end