python xlsxwriter没有图表

时间:2018-03-23 21:33:05

标签: python xlsxwriter

我想用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()

1 个答案:

答案 0 :(得分:2)

如果数组中有数据,程序应该可以工作。以下是带有示例数据的代码的略微修改版本:

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