jmcnamara / XlsxWriter

A Python module for creating Excel XLSX files.
https://xlsxwriter.readthedocs.io
BSD 2-Clause "Simplified" License
3.65k stars 633 forks source link

How to save the chart object as a png file? #1045

Closed bhishanpdl closed 8 months ago

bhishanpdl commented 8 months ago

Question

In the following tutorial code, how can we export the chart as 'chart.png' and save it?

import xlsxwriter

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

# Add the worksheet data to be plotted.
data = [10, 40, 50, 20, 10, 50]
worksheet.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': '=Sheet1!$A$1:$A$6'})

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

workbook.close()
jmcnamara commented 8 months ago

how can we export the chart as 'chart.png' and save it

Unfortunately, that isn’t possible with Xlsxwriter. Excel doesn’t store charts as images in the file format. It stores them as XML.

Excel can generate PNGs from charts at runtime from the app but that is a function of the app. Maybe try Matplotlib.

bhishanpdl commented 8 months ago

Thanks for the clarification. We can close the issue.