使用 openpyxl 和 python 更改 Excel 图表系列的名称

问题描述 投票:0回答:1

因此,我正在使用 Openpyxl 制作一些折线图,为了制作它们,我将字典的关键字符串(将作为工作簿的输入)更改为不相等并且始终是不同的字符串,因此数据不会' t 覆盖,因为某些关键字符串是相等的。
问题出在图表系列名称中,我需要它们保持不变,而不是数据列中的标题,而是我存储在其他列表中的不变字符串。>br>

是否可以只更改图表中的系列名称而保留列名称不变? (如果列名称更改为名称,我希望系列名称成为它将存在多个具有相同名称的列。)

这是我的代码:

x_values = Reference(sheet, min_col=1, min_row=2, max_col=1, max_row=sheet.max_row)
y_values = Reference(sheet, min_col=column_init, min_row=row_num, max_col=column_end, max_row=sheet.max_row)

Create the chart
chart = LineChart()
chart.add_data(data)

chart.style = 12

chart.add_data(y_values, titles_from_data=True)
chart.set_categories(y_values)
chart.set_categories(x_values)
chart.x_axis.number_format = 'hh:mm'  # 'dd-mm-yyyy hh:mm:ss'
chart.x_axis.majorTimeUnit = "hours"
chart.x_axis.title = "Date"

graph_location = E2

sheet.add_chart(chart, graph_location)

book.save(excel_name)

我尝试更改系列标题,但这不正确,并且会引发有关对象类型的错误。

chart.series.title = "SeriesName-bup"
python excel openpyxl series
1个回答
0
投票

不要使用

titles_from_data=True
,而是为您的数据创建系列并根据需要设置标题

x_values = Reference(sheet, min_col=1, min_row=2, max_col=1, max_row=sheet.max_row)
series1 = Series(x_values, title='Whatever')
...

chart.append(series1)

还需要从“openpyxl.chart”导入“Series”。

© www.soinside.com 2019 - 2024. All rights reserved.