簡體   English   中英

使用Python和Win32com刪除Excel圖中的圖例

[英]Delete legend in an Excel plot with Python and win32com

我已經有了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的第一步是記錄一個宏,該宏可以執行您想要執行的操作並進行檢查。

我錄制了一個宏,其中刪除了圖例並調整了圖表的大小,這是生成的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM