Pandas / xlsxwriter writer.close() does not completely close the excel file

喜夏-厌秋 提交于 2021-01-28 02:41:34

问题


I'm trying to modify manually an excel file after creating it with a python script. Unfortunately, if the script is still running, a sharing file violation error message appears when trying to save it with the same name.

Everything runs smoothly in the code. The file is created, filled and saved. I can open it and work on it but can't overwrite it under the same name if the script is still running.

outpath = filedialog.asksaveasfile(
    mode="wb",
    filetype=[("Excel", ("*.xls", "*.xlsx"))],
    defaultextension=".xlsx",
)
writer = pd.ExcelWriter(outpath, engine="xlsxwriter")
df1.to_excel(writer, sheet_name="Results")
writer.save()
writer.close()

I expect python to fully close the excel file and let me overwrite on it while the script is still running


回答1:


Your code looks too complicated, you don't need to deal with the writer yourself df.to_excel() can do it for you. Just use the simpler code:df1.to_excel(outpath, sheet_name="Results", engine='xlsxwriter') as suggested in the docs.




回答2:


I was facing a similar situation. The suggestion given by alec_djinn didn't work for multiple sheets, as I was working. So I just ignored .close() method and it worked just fine.



来源:https://stackoverflow.com/questions/56751070/pandas-xlsxwriter-writer-close-does-not-completely-close-the-excel-file

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