In Openpyxl, you can control the appearance of your charts using the style attribute of the Chart object. Here are the different ways to set chart styles:

  1. 'default': Uses the default chart style.
  2. 'none': Applies no style to the chart.
  3. '10', '11', '12', etc.: Applies built-in style numbers. Refer to the Openpyxl documentation for a list of available style numbers and their corresponding styles.
  4. Custom Style Objects: Utilize style objects defined in openpyxl.styles to customize chart elements. These objects include Font, Alignment, Border, and Fill, allowing for fine-grained control over font properties, text alignment, borders, and fill colors. You can find detailed information on these style objects in the Openpyxl documentation.

Here's an example demonstrating chart style customization:

from openpyxl import Workbook
from openpyxl.chart import BarChart
from openpyxl.styles import Font, Alignment

# Create workbook and worksheet
wb = Workbook()
ws = wb.active

# Add data
data = [
    ['Category', 'Value'],
    ['A', 10],
    ['B', 20],
    ['C', 30],
    ['D', 40]
]
for row in data:
    ws.append(row)

# Create chart
chart = BarChart()
chart.title = 'Chart Title'
chart.x_axis_title = 'Category'
chart.y_axis_title = 'Value'
chart.style = '10'  # Set chart style to built-in style number 10

# Customize chart styles
chart.title.font = Font(size=14, bold=True)
chart.x_axis_title.font = Font(size=12)
chart.y_axis_title.font = Font(size=12)
chart.x_axis.title.alignment = Alignment(horizontal='center')
chart.y_axis.title.alignment = Alignment(horizontal='center')

# Add chart to worksheet
ws.add_chart(chart, 'E5')

# Save workbook
wb.save('chart.xlsx')

In this example, we first create a workbook and worksheet, then add some sample data. We create a bar chart object, set its title and axis titles, and apply the built-in style number 10 using chart.style = '10'. Finally, we customize the chart's title and axis labels by setting their font properties and alignment. The chart is then added to the worksheet and the workbook is saved.

Openpyxl Chart Styling: A Guide to Setting Chart Styles

原文地址: https://www.cveoy.top/t/topic/qAfm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录