'Error when copying Excel sheet with Python xlwings library
Each month I run a report of scheduled appointments employees completed. The combined file is simple enough, each employee has their own sheet pulling from a sheet containing the full download of the month's data with INDEX/MATCH statements.
Each sheet contains a pivot table, as well as a separate section of filtered data.
I have a python script written that should work to separate each sheet into its own file, with filename equal to sheet name.
Here is my script below:
import xlwings as xw
EXCEL_FILE ='NPS_Report_Template.xlsx'
try:
excel_app = xw.App(visible=False)
wb = excel_app.books.open(EXCEL_FILE)
for sheet in wb.sheets:
sheet.api.Copy()
wb_new = xw.books.active
wb_new.save(f'{sheet.name}.xlsx')
wb_new.close()
print('success')
finally:
excel_app.quit()
The script runs successfully for the first two sheets. These sheets do not contain filtered data or a pivot table, so this is my only real lead as to what's causing the issue. The script then hits an error:
Traceback (most recent call last):
File "C:\Users\Dan\PycharmProjects\ExcelSeparator\main.py", line 12, in <module>
sheet.api.Copy()
File "C:\Users\Dan\PycharmProjects\ExcelSeparator\venv\lib\site-packages\xlwings\_xlwindows.py", line 72, in __call__
v = self.__method(*args, **kwargs)
File "C:\Users\Dan\AppData\Local\Temp\gen_py\3.9\00020813-0000-0000-C000-000000000046x0x1x9.py", line 47227, in Copy
return self._oleobj_.InvokeTypes(551, LCID, 1, (24, 0), ((12, 17), (12, 17)),Before
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "We couldn't copy this sheet.", 'xlmain11.chm', 0, -2146827284), None)
I will admit I'm a novice with the xlwings library, and to be honest I have no idea what's causing this. I feel like it should just work based on the script, but obviously I'm missing something. Any advice would be greatly appreciated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
