我正在尝试使用我的Pandas数据帧创建一个具有良好格式的excel报告。最初,我用Pandas文件覆盖了我的标题。因此,我首先编写格式化代码,关闭工作簿,然后使用openpyxl再次加载它以将我的pandas数据帧写入现有工作表。
但是,当我尝试使用writer.save()时遇到了这个错误:
AttributeError: 'Workbook' object has no attribute 'write'
这是我的代码:
output_filename = "".join(org_name.split()) + OUTPUT_FILENAME
workbook = xlsxwriter.Workbook(output_filename)
worksheet = workbook.add_worksheet()
# insert logo
worksheet.set_column('A:A', 30)
worksheet.insert_image('A1', picture, {'x_scale': 0.7, 'y_scale': 0.7})
# add titles:
title_format = workbook.add_format({'bold': True})
worksheet.write('A3', 'Report', title_format)
worksheet.write('A5', org_name, title_format)
worksheet.write('A6', 'Report Year', title_format)
worksheet.write('A7', 'Report Month', title_format)
worksheet.write('B6', THIS_YEAR)
worksheet.write('B7', calendar.month_name[THIS_MONTH])
workbook.close()
df = get_organization_df(all_df, org_name)
book = load_workbook(output_filename)
writer = pd.ExcelWriter(book, engine='openpyxl')
# get user counts
users_df = count_users(df)
users_df.to_excel(writer, sheet_name = 'Sheet1', startrow = 8)
writer.save()
提前感谢您的帮助!
答案 0 :(得分:1)
我相信你的问题在这里:writer = pd.ExcelWriter(book, engine='openpyxl')
:
book
是工作簿,而pd.ExcelWriter
的参数是字符串