python openpyxl 创建直方图实现,函数入参输入起始行号列号即可

参考openpyxl的库文档创建直方图,但例程缺乏数据范围的明确说明,让人不知如何填入数据的行列,因此做了通用函数封装

官方文档实现

from openpyxl import Workbook
from openpyxl.chart import (
BarChart,
Reference,
Series,
) w
b = Workbook()
ws = wb.active
rows = [
['Number', 'Batch 1', 'Batch 2'],
[2, 40, 30],
[3, 40, 25],
[4, 50, 30],
[5, 30, 10],
[6, 25, 5],
[7, 50, 10],
] f
or row in rows:
ws.append(row)
chart = BarChart()
chart.title = "Bar Chart"
chart.style = 10
chart.x_axis.title = 'Test'
chart.y_axis.title = 'Percentage'
cats = Reference(ws, min_col=1, min_row=1, max_row=7)
data = Reference(ws, min_col=2, min_row=1, max_col=3, max_row=7)
chart.add_data(data, titles_from_data=True)
chart.set_categories(cats)
ws.add_chart(chart, "A10")
wb.save("BarChart.xlsx")

我的封装实现,实测可行

import openpyxl
from openpyxl.chart import BarChart, Series, Reference
def Bar_Chart(start_row_data, end_row_data, start_col_data, end_col_data):
    wb = openpyxl.Workbook()
    ws = wb.active
    rows = [
        ('Number', 'Batch 1', 'Batch 2'),
        (2, 10, 30),
        (3, 40, 60),
        (4, 50, 70),
        (5, 20, 10),
        (6, 10, 40),
        (7, 50, 30),
    ]
    for row in rows:
        ws.append(row)
    chart1 = BarChart()
    chart1.type = "col"
    chart1.style = 10
    chart1.title = "Bar Chart"
    chart1.y_axis.title = 'Test number'
    chart1.x_axis.title = 'Sample length (mm)'
    data = Reference(ws, min_col=start_col_data + 1, min_row=start_row_data, max_row=end_row_data, max_col=end_col_data)
    cats = Reference(ws, min_col=start_col_data, min_row=start_row_data + 1, max_row=end_row_data)
    chart1.add_data(data, titles_from_data=True)
    chart1.set_categories(cats)
    chart1.shape = 4
    ws.add_chart(chart1, "A10")
    wb.save("barchar.xlsx")

你可能感兴趣的:(编程语言,python)