gpt4 book ai didi

Python不会关闭excel工作簿

转载 作者:行者123 更新时间:2023-12-03 16:57:33 25 4
gpt4 key购买 nike

运行代码后,我似乎无法打开生成的excel文件,因为我的电脑说它是“在另一个程序中打开”。如果我关闭python,那么我可以打开它。
当我尝试向代码添加“workbook.close()”时,出现错误“在已关闭的文件上调用 close()”。所以看起来python已经关闭了它。
我该怎么做才能在不必关闭 python 的情况下看到我的输出?

import pandas as pd

# Import data
df = pd.read_excel (r'C:\Users\Desktop\work\charts\constraints.xlsx' , sheet_name='biggestobstacle')
print (df)


# File 2 is the new excel table with the chart. Hence, we keep the originals untouched. We create a new excel + chart.
writer = pd.ExcelWriter("file2.xlsx", engine="xlsxwriter")
df.to_excel(writer, sheet_name='biggestobstacle')

# Get xlsxwriter objects
workbook = writer.book
worksheet = writer.sheets['biggestobstacle']

# Create a 'column' chart
chart = workbook.add_chart({'type': 'column'})
# select the values of the series and set a name for the series
chart.add_series({
'values': '=\'biggestobstacle\'!$B$2:$B$8',
"name": "My Series's Name"
})
# Insert the chart into the worksheet in the D2 cell
worksheet.insert_chart('D2', chart)

writer.save()

# This last line generates an error.
workbook.close()

最佳答案

从:
https://github.com/pandas-dev/pandas/blob/v1.2.3/pandas/io/excel/_base.py#L584-L900
看起来你只是 .close() 而不要担心 save()
来自 excelWriter 类

def close(self):
"""synonym for save, to make it more file-like"""
content = self.save()
self.handles.close()
return content

关于Python不会关闭excel工作簿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66800362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com