Python:Pandas.ExcelWriter,当我们尝试使用sheets函数时,遇到一个奇怪的keyerror

时间:2019-11-19 15:16:59

标签: python pandas xlsxwriter

请帮助,我不知道为什么会发生此错误。我以前使用此代码没有任何问题。我希望这不是愚蠢的事情。永远感谢您的帮助。

版本:

python 3.6

pd 0.23.0

xlsxwriter 1.0.4

writer = pd.ExcelWriter('Output.xlsx', engine='xlsxwriter')
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

输出:

Traceback (most recent call last):
File "/opt/eclipse/dropins/plugins/org.python.pydev.core_7.2.0.201903251948/pysrc/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec
exec(exp, global_vars, local_vars)
File "<console>", line 1, in <module>
KeyError: 'Sheet1'

2 个答案:

答案 0 :(得分:2)

您没有创建工作表1。

来自here的例子:

import pandas as pd

# Create a Pandas dataframe from the data.
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1') ***#this is where you create Sheet 1***

# Get the xlsxwriter objects from the dataframe writer object.
workbook  = writer.book
worksheet = writer.sheets['Sheet1'] ***#here is where you select it***

答案 1 :(得分:0)

如果您使用的是熊猫,则应使用.to_excel函数。会更容易! :)