1

我的 Python 脚本将数据放入 Excel 工作表并在同一个工作表上绘制我想要的数据。有谁知道我如何删除/隐藏情节中的图例并调整情节的大小?这是我目前的代码:

chart = xlApp.Charts.Add()
series = chart.SeriesCollection(1)
series.XValues = xlSheet.Range("L13:L200")
series.Values = xlSheet.Range("M13:M200")
series.Name = file
chart.Location(2, xlSheet.Name)
4

1 回答 1

1

弄清楚 Excel COM API 的第一步是记录一个执行您想要执行的操作的宏并检查它。

我录制了一个删除图例并调整图表大小的宏,这是生成的 VBA:

Sub Macro3()
'
' Macro3 Macro
'

'
    ActiveChart.Legend.Select
    Selection.Delete
    ActiveSheet.ChartObjects("Chart 1").Activate
End Sub

遗憾的是,它没有记录图表的大小调整,但确实记录了删除图例。这是翻译成 Python 的 VBA:

chart.Legend.Delete()

幸运的是,Google 为我们提供了如何使用 VBA 更改图表的大小或位置?翻译成 Python:

chart.Parent.Height = new_height
chart.Parent.Width = new_width
chart.Parent.Top = v_position
chart.Parent.Left = h_position

编辑:这是一个在 Excel 2003 下执行所有这些操作的简短脚本。

import win32com.client
import re

xl = win32com.client.Dispatch('Excel.Application')
xl.Visible=True
wb = xl.Workbooks.Add()
ws = wb.Sheets(1)
values = [['a','b','c'],
          [ 1,  2,  3 ],
          [ 4,  5,  6 ]]
for nrow, row in enumerate(values):
    for ncol, item in enumerate(row):
        xl.Cells(nrow+1, ncol+1).Value = item

xl.Range("A1:C3").Select()
chart = xl.Charts.Add()

# chart.Legend.Delete only works while it's a chart sheet.
# so get this done before changing the chart location!
chart.Legend.Delete()

# Excel changes the name of the chart when its location is changed.
# The new name inserts a space between letters and numbers.
# 'Chart1' becomes 'Chart 1'
new_chart_name = re.sub(r'(\D)(\d)', r'\1 \2', chart.Name)
chart.Location(2, ws.Name)

# After changing the location the reference to chart is invalid.
# We grab the new chart reference from the Shapes collection using the new name.
# If only one chart is on sheet you can also do: chart = ws.Shapes(1)
chart = ws.Shapes(new_chart_name)

chart.Top = 1
chart.Left = 1
chart.Width = 500
chart.Height = 400
于 2012-11-12T21:31:56.963 回答