弄清楚 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