gpt4 book ai didi

python xlsxwriter 缺少图表

转载 作者:行者123 更新时间:2023-12-01 02:02:28 25 4
gpt4 key购买 nike

我想用 python xlsxwriter 构建一个图表,但结果我在保存的文件中没有图表。

这是我的代码:

import xlsxwriter
from sys import stdin
workbook = xlsxwriter.Workbook('res.xlsx')
worksheet = workbook.add_worksheet()
data = []
for stroka in stdin:
######
if stroka == '\n':
break
######
stroka = stroka.split()
data.append((stroka[0], stroka[1]))
for row, (name, val) in enumerate(data):
worksheet.write(row, 0, name)
worksheet.write(row, 1, val)
chart = workbook.add_chart({'type': 'pie'})
chart.add_series({'values': '=Sheet1!B1:B' + str(row + 1)})
worksheet.insert_chart('C3', chart)
workbook.close()

最佳答案

如果数组中有数据,程序应该可以运行。这是带有示例数据的代码的稍微修改版本:

import xlsxwriter


workbook = xlsxwriter.Workbook('res.xlsx')
worksheet = workbook.add_worksheet()

data = [('apple', 60), ('cherry', 30), ('pecan', 10)]

for row, (name, val) in enumerate(data):
worksheet.write(row, 0, name)
worksheet.write(row, 1, val)

chart = workbook.add_chart({'type': 'pie'})
chart.add_series({'values': '=Sheet1!B1:B' + str(row + 1)})

worksheet.insert_chart('A5', chart)

workbook.close()

输出:

enter image description here

但是,您可能还想添加一个类别,如下所示。请注意,这使用了 add_series() 中的替代列表语法:

import xlsxwriter


workbook = xlsxwriter.Workbook('res.xlsx')
worksheet = workbook.add_worksheet()

data = [('apple', 60), ('cherry', 30), ('pecan', 10)]

for row, (name, val) in enumerate(data):
worksheet.write(row, 0, name)
worksheet.write(row, 1, val)

chart = workbook.add_chart({'type': 'pie'})
chart.add_series({'categories': ['Sheet1', 0, 0, row, 0],
'values': ['Sheet1', 0, 1, row, 1]})

worksheet.insert_chart('A5', chart)

workbook.close()

输出:

enter image description here

关于python xlsxwriter 缺少图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49458565/

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