In this Python article we are going to learn How to Plot PieChart in Excel with Python ,
for working with Microsoft Excel in Python we need to use a third party library, the library that
we are going to use is XlsxWriter library. so it is is a Python module for writing files in the
Excel 2007+ XLSX file format. XlsxWriter can be used to write text, numbers, formulas and
hyperlinks to multiple worksheets and it supports features such as formatting and many more.
It supports Python 2.7, 3.4+ and PyPy and uses standard libraries only.
This is the complete source code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# import xlsxwriter module import xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create. workbook = xlsxwriter.Workbook("chart_pie.xlsx") # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # here we create bold format object . bold = workbook.add_format({'bold':1}) # this is our data with data list headings = ['Category', 'Values'] data = [ ['Python', 'C++', 'Java'], [70, 20, 10], ] # Write a row of data starting from 'A1' # with bold format. worksheet.write_row('A1', headings, bold) # Write a column of data starting from # A2, B2, C2 respectively. worksheet.write_column('A2', data[0]) worksheet.write_column('B2', data[1]) #this is the type of chart chart1 = workbook.add_chart({'type': 'pie'}) # Add a data series to a chart chart1.add_series({ 'name':'Popularity Chart', 'categories':['Sheet1', 1,0,3,0], 'values':['Sheet1', 1,1,3,1], }) #set the title for the chart chart1.set_title({'name':'Programming Language Chart'}) #set the style for the chart chart1.set_style(10) #insert chart to the worksheet worksheet.insert_chart('C2', chart1, {'x_offset':25, 'y_offset':10}) #close the workbook workbook.close() |
The first thing you need to create a workbook, you can use this code for creating workbook,
make sure that you give the name of the workbook.
1 |
workbook = xlsxwriter.Workbook("chart_pie.xlsx") |
Using this code you can make the text of workbook in bold style.
1 |
bold = workbook.add_format({'bold':1}) |
So using this code you can specify the type of chart that you want.
1 |
chart1 = workbook.add_chart({'type': 'pie'}) |
This is used for setting the title of the chart.
1 |
chart1.set_title({'name':'Programming Language Chart'}) |
Run the complete code and after that check your working directory for the excel file, open the
file and this is the result.

Join Our Free Courses