我在jupyter notebook同样的代码能正常写入excel并成功写入图片,但在pycharm老是报错,我核对了虚拟环境和pandas的包,确定是在同一个虚拟环境,pandas的包都是一样的,但就是一直报错,为此我查了几个小时,一晚上都没解决,周一来上班,我又继续尝试,没想到一个小时我就解决了,居然只需要加一个参数
'Workbook' object has no attribute 'sheetnames'
报错代码
all_cols_list = [
['一级分类', v1_df],
['二级分类', v2_df],
['实体', entity_df],
['泛化实体', generate_en_df],
['话题', topic_df],
['账号', guid_df],
['小时关注人数', hour_df],
['访问频率', freq_df],
['访问次数', times_df]]
img_path_dic = {
"一级分类": self.get_path("v1.png"),
"二级分类": self.get_path("v2.png"),
"实体": self.get_path("entity.png"),
"泛化实体": self.get_path("generate.png"),
"话题": self.get_path("topic.png"),
"账号": self.get_path("guid.png"),
"小时关注人数": self.get_path("hour.png"),
"访问频率": self.get_path("freq.png"),
"访问次数": self.get_path("times.png")
def save_data_to_excel(self, save_name, all_cols_list, img_path_dic):
writer = pd.ExcelWriter(save_name)
for sheet_name, df_item in all_cols_list:
df_item.to_excel(writer, sheet_name=sheet_name, index=False)
sheet = writer.book.sheetnames[sheet_name]
sheet.insert_image('H2', img_path_dic[sheet_name])
writer.save()
writer.close()
我换了好多excel的包,xlrd, xlsxwriter 都不行,我尝试xlsxwriter是能成功写入图片和数据的,我偶然在一篇博客看到在pd.ExcelWriter(save_name)加一个参数engine=‘xlsxwriter’,我照着加这个参数,最后运行,竟然被解决了,可能是pycharm和jupyter内部调用包的时候各自的默认参数不一样导致,不管怎么样,解决了,我将这个bug记录下来,希望遇到的人能快速解决
加一个参数即可
def save_data_to_excel(self, save_name, all_cols_list, img_path_dic):
writer = pd.ExcelWriter(save_name, engine='xlsxwriter')
for sheet_name, df_item in all_cols_list:
df_item.to_excel(writer, sheet_name=sheet_name, index=False)
sheet = writer.book.sheetnames[sheet_name]
sheet.insert_image('H2', img_path_dic[sheet_name])
writer.save()
writer.close()