SoFunction
Updated on 2024-11-19

Generate Cool Excel Charts with Python

preamble

This article on Python automate the operation of Excel and generate charts, a detailed analysis and description of the

Let's take a look at a comparison of common libraries in python that can manipulate Excel

storehouse

XlsxWriter is a python module for writing Excel 2007 and xlsx file formats. It can be used to write text, numbers, formulas and support for cell formatting, images, charts, document configuration, auto-filtering and other features

Benefits: more features, high fidelity documents, extended format types, faster and configurable

Cons: cannot be used to read and modify excel files

Official Documentation:/

2. Generate line graphs

# -*- coding:utf-8 -*-

import xlsxwriter

# Create an excel
workbook = ("chart_line.xlsx")
# Create a sheet
worksheet = workbook.add_worksheet()
# worksheet = workbook.add_worksheet("bug_analysis")

# Custom styles, bolded
bold = workbook.add_format({'bold': 1})

# --------1, prepare data and write to excel ---------------
# Write data to excel, to be used when creating icons
headings = ['Number', 'testA', 'testB']
data = [
    ['2017-9-1', '2017-9-2', '2017-9-3', '2017-9-4', '2017-9-5', '2017-9-6'],
    [10, 40, 50, 20, 10, 50],
    [30, 60, 70, 50, 40, 30],
]

# Write to table header
worksheet.write_row('A1', headings, bold)

# Write data
worksheet.write_column('A2', data[0])
worksheet.write_column('B2', data[1])
worksheet.write_column('C2', data[2])

# --------2, generate charts and insert into excel ---------------
# Create a bar chart (line chart)
chart_col = workbook.add_chart({'type': 'line'})

# Configure the first series of data
chart_col.add_series({
    # Here sheet1 is the default value, because we didn't specify a sheet name when we created the new sheet.
    # If we set the sheet name when we create a new sheet, we have to set it to the appropriate value here.
    'name': '=Sheet1!$B$1',
    'categories': '=Sheet1!$A$2:$A$7',
    'values':   '=Sheet1!$B$2:$B$7',
    'line': {'color': 'red'},
})

# Configure the second series of data
chart_col.add_series({
    'name': '=Sheet1!$C$1',
    'categories':  '=Sheet1!$A$2:$A$7',
    'values':   '=Sheet1!$C$2:$C$7',
    'line': {'color': 'yellow'},
})

# Configure the second series of data (another syntax is used)
# chart_col.add_series({
#     'name': ['Sheet1', 0, 2],
#     'categories': ['Sheet1', 1, 0, 6, 0],
#     'values': ['Sheet1', 1, 2, 6, 2],
#     'line': {'color': 'yellow'},
# })

# Set the title of the chart and the x, y axis information
chart_col.set_title({'name': 'The xxx site Bug Analysis'})
chart_col.set_x_axis({'name': 'Test number'})
chart_col.set_y_axis({'name':  'Sample length (mm)'})

# Set the style of the chart
chart_col.set_style(1)

# Insert the chart into the worksheet and set the offset
worksheet.insert_chart('A10', chart_col, {'x_offset': 25, 'y_offset': 10})

()

3. Generate bar charts

# -*- coding:utf-8 -*-

import xlsxwriter

# Create an excel
workbook = ("chart_column.xlsx")
# Create a sheet
worksheet = workbook.add_worksheet()
# worksheet = workbook.add_worksheet("bug_analysis")

# Custom styles, bolded
bold = workbook.add_format({'bold': 1})

# --------1, prepare data and write to excel ---------------
# Write data to excel, to be used when creating icons
headings = ['Number', 'testA', 'testB']
data = [
    ['2017-9-1', '2017-9-2', '2017-9-3', '2017-9-4', '2017-9-5', '2017-9-6'],
    [10, 40, 50, 20, 10, 50],
    [30, 60, 70, 50, 40, 30],
]

# Write to table header
worksheet.write_row('A1', headings, bold)

# Write data
worksheet.write_column('A2', data[0])
worksheet.write_column('B2', data[1])
worksheet.write_column('C2', data[2])

# --------2, generate charts and insert into excel ---------------
# Create a column chart
chart_col = workbook.add_chart({'type': 'column'})

# Configure the first series of data
chart_col.add_series({
    # Here sheet1 is the default value, because we didn't specify a sheet name when we created the new sheet.
    # If we set the sheet name when we create a new sheet, we have to set it to the appropriate value here.
    'name': '=Sheet1!$B$1',
    'categories': '=Sheet1!$A$2:$A$7',
    'values':   '=Sheet1!$B$2:$B$7',
    'line': {'color': 'red'},
})

# Configure the second series of data (another syntax is used)
chart_col.add_series({
    'name': '=Sheet1!$C$1',
    'categories':  '=Sheet1!$A$2:$A$7',
    'values':   '=Sheet1!$C$2:$C$7',
    'line': {'color': 'yellow'},
})

# Configure the second series of data (another syntax is used)
# chart_col.add_series({
#     'name': ['Sheet1', 0, 2],
#     'categories': ['Sheet1', 1, 0, 6, 0],
#     'values': ['Sheet1', 1, 2, 6, 2],
#     'line': {'color': 'yellow'},
# })

# Set the title of the chart and the x, y axis information
chart_col.set_title({'name': 'The xxx site Bug Analysis'})
chart_col.set_x_axis({'name': 'Test number'})
chart_col.set_y_axis({'name':  'Sample length (mm)'})

# Set the style of the chart
chart_col.set_style(1)

# Insert charts into worksheets and offsets
worksheet.insert_chart('A10', chart_col, {'x_offset': 25, 'y_offset': 10})
()

4. Generate pie charts

# -*- coding:utf-8 -*-

import xlsxwriter

# Create an excel
workbook = ("chart_pie.xlsx")
# Create a sheet
worksheet = workbook.add_worksheet()

# Custom styles, bolded
bold = workbook.add_format({'bold': 1})

# --------1, prepare data and write to excel ---------------
# Write data to excel, to be used when creating icons
data = [
    ['closed', 'active', 'reopen', 'NT'],
    [1012, 109, 123, 131],
]

# Write data
worksheet.write_row('A1', data[0], bold)
worksheet.write_row('A2', data[1])

# --------2, generate charts and insert into excel ---------------
# Create a bar chart (pie chart)
chart_col = workbook.add_chart({'type': 'pie'})

# Configure the first series of data
chart_col.add_series({
    'name': 'Bug Analysis',
    'categories': '=Sheet1!$A$1:$D$1',
    'values': '=Sheet1!$A$2:$D$2',
    'points': [
        {'fill': {'color': '#00CD00'}},
        {'fill': {'color': 'red'}},
        {'fill': {'color': 'yellow'}},
        {'fill': {'color': 'gray'}},
    ],

})

# Set the title of the chart and the x, y axis information
chart_col.set_title({'name': 'Bug Analysis'})

# Set the style of the chart
chart_col.set_style(10)

# Insert charts into worksheets and offsets
worksheet.insert_chart('B10', chart_col, {'x_offset': 25, 'y_offset': 10})
()

5. Practical development

xlswriter new and write to Excel

# 3.6.2 xlswriter new and write to Excel
def fun3_6_2():
    # Create Exce and add sheets
    workbook = ('')
    worksheet = workbook.add_worksheet()

    # Set column widths
    worksheet.set_column('A:A', 20)

    # Set the format
    bold = workbook.add_format({'bold': True})

    # Add text content
    ('A1', 'Hello')

    # Add content by format
    ('A2', 'World', bold)

    # Write some numbers
    (2, 0, 123)
    (3, 0, 123.456)

    # Add a picture
    worksheet.insert_image('B5', '')

    ()

Above is the use of Python to generate Excel cool charts in detail, more information about Python Excel charts please pay attention to my other related articles!