gpt4 book ai didi

python - 如何使用 XlsxWriter 自动定义 excel 工作表名称?

转载 作者:行者123 更新时间:2023-11-28 17:04:24 27 4
gpt4 key购买 nike

有没有办法根据 pandas 数据框中单元格的值动态命名 excel 工作表?

这是我所拥有的:

#dataframe cell i want to work as sheet name is here
df_storename = df_store.loc[1, 'Store']

writer = pd.ExcelWriter('payroll.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df_store.to_excel(writer, sheet_name=df_storename)

workbook = writer.book
worksheet1 = writer.sheets[df_storename]
worksheet2 = workbook.add_worksheet('One-on-One')

chart = workbook.add_chart({'type': 'column'})
chart1 = workbook.add_chart({'type': 'column'})

chart.add_series({'values': '=df_storename!$F$0:$F$9', 'name':
'Service Sales', 'categories':
'=df_storename!$C$2:$C$11'})
chart1.add_series({'values': '=df_storename!$P$0:$P$9',
'name': 'Paid Back Bar %', 'categories':
'=df_storename!$C$2:$C$11'})

最佳答案

最好的方法是使用 add_series() 中的列表语法而不是 A1:C8 范围语法。例如:

import pandas as pd

# Create a Pandas dataframe from some data.
df_store = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
df_storename = 'My Storename'

writer = pd.ExcelWriter('payroll.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df_store.to_excel(writer, sheet_name=df_storename)

workbook = writer.book
worksheet1 = writer.sheets[df_storename]
worksheet2 = workbook.add_worksheet('One-on-One')

chart = workbook.add_chart({'type': 'column'})


chart.add_series({'name': 'Service Sales',
'categories': [df_storename, 1, 0, 7, 0],
'values': [df_storename, 1, 1, 7, 1]})

worksheet2.insert_chart('D2', chart)

writer.save()

输出:

enter image description here

通过这种方式,您可以使用数据框的大小设置要绘制的单元格范围。有关更实际的示例,请参阅 XlsxWriter Pandas chart examples .

关于python - 如何使用 XlsxWriter 自动定义 excel 工作表名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52012134/

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