Question

I m working with xlswriter to generate Excel files in python. I'm referring [this link] for tutorial.

In this under section Chart series option: Points, I copied the code and ran it. it works but I need to remove the following lines as they are not required.

worksheet.write_column('A1', data[0])
worksheet.write_column('B1', data[1])

These lines give me the values of the pie chart data in textua format in cells A1 and B1, which I dont want.

But when I remove them, the pie chart also gets removed. I dont know why. Where I'm going wrong

Here is the code.

import xlsxwriter

workbook = xlsxwriter.Workbook('chart_pie.xlsx')

worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'pie'})

data = [
    ['Pass', 'Fail'],
    [90, 10],
]

worksheet.write_column('A1', data[0])# these lines gets printed on top left corner, which I dont want.
worksheet.write_column('B1', data[1])

chart.add_series({
    'categories': '=Sheet1!$A$1:$A$2',
    'values':     '=Sheet1!$B$1:$B$2',
    'points': [
        {'fill': {'color': 'green'}},
        {'fill': {'color': 'red'}},
    ],
})

worksheet.insert_chart('C3', chart)

workbook.close()
Was it helpful?

Solution

I can add the data to another worksheet. And then refer the data from that worksheet.

Demo

import xlsxwriter

workbook = xlsxwriter.Workbook('chart_line.xlsx')
worksheet = workbook.add_worksheet()
worksheet1 = workbook.add_worksheet()
# Add the worksheet data to be plotted.
data = [10, 40, 50, 20, 10, 50]
worksheet1.write_column('A1', data)

# Create a new chart object.
chart = workbook.add_chart({'type': 'line'})

# Add a series to the chart.
chart.add_series({'values': '=Sheet2!$A$1:$A$6'})

# Insert the chart into the worksheet.
worksheet.insert_chart('C1', chart)

workbook.close()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top