使用openpyxl配置ChartLines对象时的网格线颜色异常问题
OpenPyXL 图表网格线颜色设置问题解决
问题描述
使用openpyxl绘制折线图时,配置垂直网格线颜色不生效。代码中已设置黄色填充,但运行后网格线仍为默认颜色,仅刻度间隔(每4个刻度显示)符合预期。
示例代码
# Import from openpyxl import Workbook from openpyxl.chart import LineChart, Reference from openpyxl.chart.axis import ChartLines, TextAxis from openpyxl.chart.shapes import GraphicalProperties from openpyxl.drawing.colors import ColorChoice # Create a line chart chart = LineChart() # Reference data from the worksheet I'm working with num_rows = ws_data.max_row num_cols = ws_data.max_column data_ref = Reference(ws_data, min_col=2, min_row=1, max_col=num_cols, max_row=num_rows) chart.add_data(data_ref, titles_from_data=True) # Configure the x_axis chart.x_axis = TextAxis(tickMarkSkip=4) chart.x_axis.majorTickMark = "cross" chart.x_axis.delete = False # Configure the vertical gridlines chart.x_axis.majorGridlines = ChartLines() chart.x_axis.majorGridlines.graphicalProperties = GraphicalProperties(noFill=False, solidFill=ColorChoice(prstClr='yellow')) # Add the chart to the 'Charts' worksheet ws_chart.add_chart(chart, "A1")
解决方案
问题根源在于网格线的图形属性设置错误,openpyxl中线条样式需通过LineProperties定义,而非直接使用solidFill。修改网格线配置部分代码即可解决:
修改后的关键代码
# 新增必要导入 from openpyxl.chart.shapes import LineProperties from openpyxl.drawing.colors import SchemeColor # Configure the vertical gridlines chart.x_axis.majorGridlines = ChartLines() # 创建线条属性,设置颜色和宽度 line_props = LineProperties(solidFill=SchemeColor(prstClr='yellow'), w=1000) # w为线条宽度,单位EMU # 将线条属性传入GraphicalProperties的ln参数 chart.x_axis.majorGridlines.graphicalProperties = GraphicalProperties(ln=line_props)
完整修改后代码
from openpyxl import Workbook from openpyxl.chart import LineChart, Reference from openpyxl.chart.axis import ChartLines, TextAxis from openpyxl.chart.shapes import GraphicalProperties, LineProperties from openpyxl.drawing.colors import SchemeColor # Create a line chart chart = LineChart() # Reference data from the worksheet I'm working with num_rows = ws_data.max_row num_cols = ws_data.max_column data_ref = Reference(ws_data, min_col=2, min_row=1, max_col=num_cols, max_row=num_rows) chart.add_data(data_ref, titles_from_data=True) # Configure the x_axis chart.x_axis = TextAxis(tickMarkSkip=4) chart.x_axis.majorTickMark = "cross" chart.x_axis.delete = False # Configure the vertical gridlines chart.x_axis.majorGridlines = ChartLines() line_props = LineProperties(solidFill=SchemeColor(prstClr='yellow'), w=1000) chart.x_axis.majorGridlines.graphicalProperties = GraphicalProperties(ln=line_props) # Add the chart to the 'Charts' worksheet ws_chart.add_chart(chart, "A1")
说明
LineProperties用于定义线条的样式,包括颜色、宽度、虚线类型等- 若需自定义颜色,可替换
SchemeColor为RGBColor,传入RGB值(如RGBColor(255,255,0)表示黄色) w参数为线条宽度,单位是EMU(1pt=12700 EMU),设置为1000对应约0.08pt的细线
内容的提问来源于stack exchange,提问作者ensbana
相关产品推荐
相关产品推荐

