使用Python和win32com删除Excel图中的图例

我有我的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) 

计算Excel COM API的第一步是logging一个macros,它可以执行你想要做的事情并检查它。

我logging了一个macros的删除图例和调整图表,这里是由此产生的VBA:

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

可悲的是,它没有logging图表的大小调整,但它logging了删除图例。 这里是VBA翻译成Python:

 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