Search code examples
pythonexcelopenpyxl

Fail to change the stacked bar chart style by openpyxl. How to fix it?


Current Style

Current Style

Target Style

Target Style

When I generate a percentage stacked bar chart by openpyxl, I would like it as the target style in the image attached. But what I got is the current one. The code is as below. I tried change the chart.style number. It doesn't work. Environment: Window 10 + Python 3.10 (VS 2017) + Excel 365

def chart_add_A(filename):
    workbook = load_workbook(filename)
    worksheet = workbook['A']
    
    chart_data = Reference(worksheet, min_row = 2, max_row = worksheet.max_row, min_col = 2, max_col = 3)
    chart_series = Reference(worksheet, min_row = 2, max_row = worksheet.max_row, min_col = 1, max_col = 1)
    chart_A = BarChart()
    chart_A.type = 'col'
    chart_A.style = 3
    chart_A.grouping = "percentStacked"
    chart_A.title = 'A'
    chart_A.x_axis.title = 'Month'
    chart_A.y_axis.title = 'Count'
    chart_A.legend = None
    chart_A.dLbls=label.DataLabelList()
    chart_A.dLbls.showVal=True
    chart_A.showVal = True
    chart_A.width = 24
    chart_A.height = 12
    chart_A.add_data(chart_data)
    chart_A.set_categories(chart_series)
    worksheet.add_chart(chart_A, 'A0')
    workbook.save(filename)

How can I get the target style to save the chart in excel? Thanks


Solution

  • Referenced in the Openpyxl documentation,
    Stacked Bar Charts should have their overlap set to 100.

    Need to add the following setting;

    chart_A.overlap = 100