如何用Python 3.7+Openpyxl 2.5.12设置主网格线为点样式?
Setting Dotted Major Gridlines in ScatterChart with openpyxl 2.5.12
Great question! In openpyxl 2.5.12, you absolutely can set dotted styles for major gridlines—you just need to target the gridlines through the chart's axis objects instead of the series. Here's how to make it work:
The Key: Access Gridlines via Axis Objects
Unlike series lines, major gridlines are tied directly to the chart's X and Y axes. You'll need to access the majorGridlines property of each axis, then modify its line style just like you did for your series.
Working Code Example
Here's a complete, tested example that sets dotted lines for both X and Y major gridlines, plus your existing series dotted style:
from openpyxl import Workbook from openpyxl.chart import ScatterChart, Reference, Series # Create workbook and worksheet wb = Workbook() ws = wb.active # Populate test data for i in range(1, 11): ws.append([i, i*i]) # Initialize scatter chart chart = ScatterChart() # Define data ranges for the series x_vals = Reference(ws, min_col=1, min_row=1, max_row=10) y_vals = Reference(ws, min_col=2, min_row=1, max_row=10) # Create and configure series (your existing working code) series = Series(y_vals, x_vals, title="Sample Data") series.graphicalProperties.line.dashStyle = "sysDot" chart.series.append(series) # Set Y-axis major gridlines to dotted style y_axis = chart.y_axis y_axis.majorGridlines.graphicalProperties.line.prstDash = "dot" # Set X-axis major gridlines to dotted style x_axis = chart.x_axis x_axis.majorGridlines.graphicalProperties.line.prstDash = "dot" # Add chart to worksheet and save ws.add_chart(chart, "D1") wb.save("dotted_gridlines_chart.xlsx")
Notes for Your Version (2.5.12)
- You can use either
prstDash = "dot"ordashStyle = "sysDot"for the gridlines—both will produce a dotted line style in Excel. - If you ever need to disable gridlines later, you can set
y_axis.majorGridlines = None(but this isn't needed here since you want them visible with a style).
This approach should work perfectly on your Windows 7 system with Python 3.7 and openpyxl 2.5.12.
内容的提问来源于stack exchange,提问作者FJSJ




