python - 在 Xlwings 中设置图表名称

标签 python excel windows charts xlwings

当我用 xlwings 绘制图表时,我无法更改图表名称。图表名称和图例名称仍然是“Series 1”,但左上角显示的是我想要的“Feb sales”

import xlwings as xw

sht = xw.Book().sheets[0]
sht.range('A1').value = list(zip([1, 2, 3, 4]))
chart = sht.charts.add()
chart.set_source_data(sht.range('A1').expand())
chart.chart_type = 'line_markers'
chart.name='Feb sales'
#chart.api.ChartTitle.Text = 'Feb sales'
#chart.delete()

created chart

这是一个已知问题吗?我该如何解决这个问题?

最佳答案

这应该有效:

import xlwings as xw

sht = xw.Book().sheets[0]
sht.range('A1').value = list(zip([1, 2, 3, 4]))
chart = sht.charts.add()
chart.set_source_data(sht.range('A1').expand())
chart.chart_type = 'line_markers'

chart.api[1].SetElement(2)  # Place chart title at the top
chart.api[1].ChartTitle.Text = 'Feb sales'  # Change text of the chart title

表达式 chart.api 返回一个包含两个 COM 包装器的元组。我不太确定为什么有两个 COM 包装器,但似乎您需要第二个包装器才能访问图表。因此这里使用了 chart.api[1]

具有属性 xlwings.Chart.name你可以设置一个excel图表的Name属性(正如您在问题代码中所做的那样),但这不是用于显示的属性。要实现图表中文字的显示需要设置excel图表的ChartTitle属性(如本答案代码中所做的那样)。

关于python - 在 Xlwings 中设置图表名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44910566/

相关文章:

excel - 强制 Excel 2007 将列中的所有值视为文本

c# - 使用 C# System.DirectoryServices 在远程 Windows 服务器上进行用户管理

python - 如何在numpy中找到已编译的扩展模块

windows - hMailServer 只在第一次回复

python - 如何在动态创建的 QMdiAreaSubWindow 中处理 matplotlib pick Artist 事件? (给出的示例 - 部分工作!)

c++ - 提升 python 容器、迭代器和项目的生命周期

Python HTMLParser - 停止解析

python - 如何从python3中的单行输入将不同数据类型的值映射到单行代码中?

mysql - 如何通过 while 循环将从 2011-01-02 到 2100-01-01 的每周的第一天添加到 mysql 表中?

sql-server - Excel VBA 和 ADODB : retrieve auto identity of row inserted into SQL Server from VBA