<ValueError: Sheet already exists and if_sheet_exists is set to 'error'> on one machine but not on another

Question:

I’m running some basic python code which generates a pandas DataFrame called df and then writes it to a pre-formatted Excel file using pandas ExcelWriter and openpyxl as its engine.

workbook = load_workbook('example.xlsx')
sheet = workbook['example_sheet']
writer = pd.ExcelWriter('example.xlsx', engine='openpyxl', mode='a')
writer.book = workbook
writer.sheets = {ws.title: ws for ws in writer.book.worksheets}

sheet.cell(row=8, column=5).value = some.value
df.to_excel(writer, sheet_name='example_sheet', index=False, header=False, startrow=10, startcol=5)

The strange thing is that when running on my machine it works perfectly, however on my colleague’s machine it throws the mentioned error:

File "C:UsersuserAppDataLocalProgramsPythonPython37libsite-packagespandasioexcel_openpyxl.py", line 437, in write_cells f"Sheet '{sheet_name}' already exists and " ValueError: Sheet 'example_sheet' already exists and if_sheet_exists is set to 'error'.

I’ve tried working around it by explicitly setting

if_sheet_exists = 'replace'

however now (as expected) it replaces the entire sheet and destroys the formatting that was applied before. When running on my machine however it would not replace the sheet, even though the writer was set to do so.

I’m not entirely sure where to look for differences in the machines so if anyone could throw me an idea I would be very thankful.

Asked By: Ale Pan

||

Answers:

The last Pandas version to behave as you expect was version 1.2.5. pip uninstall pandas and then pip install pandas==1.2.5, then it will simply append the data to your previously formatted Excel template.

YMMV.

Edit:

I believe the issue was with openpyxl, which you may be able to revert separately if the above solution is not feasible. You might also try if_sheet_exists = 'overlay' if it suits your needs.

Answered By: Patrick A. Lee
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.