Moving Worsksheet after a Named Worksheet in Excel using pywin32 Dispatch

喜夏-厌秋 提交于 2021-02-04 21:06:49

问题


I have tons of files where I need to copy a certain sheet from them to another workbook, they need to be placed after a sheet with a specific name, while keeping all the formatting in the sheet that is being moved.

I saw in another thread that pywin32 would be the way to go, however I am having a hard time with copying this sheet "After" the named sheet.

xl = Dispatch("Excel.Application")

xl.Visible = True  
xl.AskToUpdateLinks = False
xl.EnableEvents = False
xl.DisplayAlerts = False

wb1 = xl.Workbooks.Open(Filename=p1)
wb2 = xl.Workbooks.Open(Filename=p2)    
ws1 = wb1.Worksheets("ThisSheet")

##PROBLEM LINE HERE
ws1.Copy(After=wb2.Worksheets("AfterThisSheet"))
##END OF PROBLEM LINE

wb2.Sheets("ThisSheet").Name = "NewNameInNewWorkBook"
wb2.Close(SaveChanges=True)
wb1.Close(SaveChanges=True)

xl.Quit()

When I use "Before" instead of "After", this operation is done successfully but unfortunately the sheet I want to copy ends in the wrong place.

When I use "After" it throws back an error.

I can use other packages in python like pandas, xlrd etc. but then, they seem to have issues with keeping the formatting intact.

Thanks in Advance


回答1:


The solution turned out to be simple actually, it seems that the Copy method required both a specification for "Before" and "After"

##PROBLEM LINE HERE
ws1.Copy(After=wb2.Worksheets("AfterThisSheet"))
##END OF PROBLEM LINE

##CORRECT STATEMENT
ws1.Copy(None, After=wb2.Worksheets("AfterThisSheet"))
##END OF CORRECT STATEMENT

So "None" should be passed to the "Before" parameter, before specifying After.



来源:https://stackoverflow.com/questions/52685699/moving-worsksheet-after-a-named-worksheet-in-excel-using-pywin32-dispatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!