Python 2.7 - win32com.client - Move a worksheet from one workbook to another -
i'm trying move 1 excel worksheet workbook workbook b python 2.7, maintain getting error.
python script:
import win32com.client excel=win32com.client.dispatch('excel.application') excel.visible=false wbp=excel.workbooks.open('c:\full path\workbooka.xlsx') wbg=excel.workbooks.open('c:\full path\workbookb.xlsx') wbg.worksheets("sheet1").select wbg.worksheets("sheet1").move(before=wbp.worksheets("annual")) wbp.saveas('c:\full path\workbooka.xlsx') excel.application.quit()
error i'm receiving:
traceback (most recent phone call last): file "c:\full path\test.py", line 10, in <module> wbg.worksheets("sheet1").select file "c:\python27\lib\site-packages\win32com\gen_py\00020813-0000-0000-c000-000000000046x0x1x8\sheets.py", line 120, in __call__ ret = self._oleobj_.invoketypes(0, lcid, 2, (9, 0), ((12, 1),),index com_error: (-2147352567, 'exception occurred.', (0, none, none, none, 0, -2147352565), none)
thank you!
solution:
see comments bernie. worksheet needed moved named charts not sheet1.
i'm writing comments in reply because it's easier read...
since error occurs on line appears problem there no "sheet1" in workbookb.xlsx
below things might want alter in code:
you can utilize win32com.client.dispatchex
create new instance of excel avoid interfering open excel instances. if utilize dispatchex
can drop setting .visible
false
. farther reading dispatchex
here: http://timgolden.me.uk/python/win32_how_do_i/start-a-new-com-instance.html
\ escape character. utilize either raw strings or forward-slashes, e.g.: wbg=excel.workbooks.open(r'c:\full path\workbookb.xlsx')
or wbg=excel.workbooks.open('c:/full path/workbookb.xlsx')
incorporating suggestions code becomes:
from win32com.client import dispatchex excel = dispatchex('excel.application') wbp=excel.workbooks.open(r'c:\full path\workbooka.xlsx') wbg=excel.workbooks.open(r'c:\full path\workbookb.xlsx') # note altered sheet name; .select not required wbg.worksheets("charts").move(before=wbp.worksheets("annual")) wbp.saveas(r'c:\full path\workbooka.xlsx') excel.quit() del excel # ensure excel process ends
python python-2.7 excel-vba win32com
No comments:
Post a Comment