Tag Archives: python2.7 ExcelWriter error

python2.7 ExcelWriter error Exception caught in workbook destructor. Explicit close() may be require

Use Pandas’ ExcelWriter to write to Excel

import pandas as pd

xlsx = pd.ExcelWriter('diff.xlsx')
for i in range(1,5):
	df = pd.DataFrame(data=[(1,2,3)])
	df.to_excel(xlsx, sheet_name='a', index=False)
df = pd.DataFrame(data=[(1,2,3)])
df.to_excel(xlsx, sheet_name='a', index=False)

Another excel write outside the for loop will report an error: Exception caught in workbook destructor. Explicit close() may be require.
this error is generally due to two reasons:

    1. needs to be saved and closed after writing the file. Add that the xlsx.save() file already exists and is open. That is to close the file and run the program
    again. This time, the code encountered a situation 1, which required xlsx.save() outside the for loop, and then write.

Still report an error after modification. A virtual environment was later created using python3.6 and still requires xlsx.save() to run successfully. The
modified python3.6 code is as follows

import pandas as pd

xlsx = pd.ExcelWriter('diff.xlsx')
for i in range(1,5):
	df = pd.DataFrame(data=[(1,2,3)])
	df.to_excel(xlsx, sheet_name='a', index=False)
df = pd.DataFrame(data=[(1,2,3)])
df.to_excel(xlsx, sheet_name='a', index=False)
xlsx.save()