使用 win32com 的 Python、Excel 和图表

问题描述 投票:0回答:2

Python 和 MS Excel 问题 - 使用 win32com,我可以在 Excel 中创建图表,但无法在工作表中移动它。我在网上找到了生成图表的代码:

import win32com.client
from win32com.client import constants as c

xl = win32com.client.gencache.EnsureDispatch('Excel.Application')
xl.Visible = True
wb = xl.Workbooks.Add()
ws = xl.ActiveSheet
ws.Range('A1').FormulaR1C1 = 'X'
ws.Range('B1').FormulaR1C1 = 'Y'
ws.Range('A2').FormulaR1C1 = 1
ws.Range('A3').FormulaR1C1 = 2
ws.Range('A4').FormulaR1C1 = 3
ws.Range('B2').FormulaR1C1 = 4
ws.Range('B3').FormulaR1C1 = 5
ws.Range('B4').FormulaR1C1 = 6
#ws.Range('A1:B4').Select()
ch = ws.Shapes.AddChart().Select()
xl.ActiveChart.ChartType = c.xlXYScatterLines
xl.ActiveChart.SetSourceData(Source=ws.Range("A1:B4"))
#ch.Location(10,10) # something like this?

如何在工作表中移动图表? enter image description here

python excel charts win32com
2个回答
3
投票

您可以在创建图表时指定位置

expression.AddChart(Type, Left, Top, Width, Height)
请参阅此处

如果您不想将图表嵌入工作表中,您可以创建图表工作表:

wb.Worksheets.Add(Type:=xlChart)

警告:Microsoft.interop.Excel 不是 win32com,但应该可以工作。


0
投票
import os 
import win32com.client
excel = win32com.client.gencache.EnsureDispatch('Excel.Application')

workbook = excel.Workbooks.Open(r'D:\\test\\report\\Test.xlsx')
worksheet = workbook.Worksheets.Item("Tablespace")
excel_reange = worksheet.Range("B4:BV14")

chart_objects = worksheet.ChartObjects()
chart_objects= chart_objects.Add(200, 100, 900, 290)
chart = chart_objects.Chart 

chart.SetSourceData(excel_reange, PlotBy=1)  ## Done
chart.ChartType = 4

chart.HasTitle = True
Chart_title = chart.ChartArea
Chart_title.Font.Size = 6

chart.HasTitle = True
Chart_title = chart.ChartTitle
Chart_title.Text = "AYU Tablespace Growth"
Chart_title.Font.Size = 12

chart.HasLegend = True
chart.Legend.Position = -4107
chart.Legend.Font.Size = 6

workbook.Save()
workbook.Close()
© www.soinside.com 2019 - 2024. All rights reserved.