Python, Excel, and Charts using win32com

匿名 (未验证) 提交于 2019-12-03 03:03:02

问题:

Python and MS Excel question - using win32com, I'm able to create a chart within Excel but i'm unable to move it within a worksheet. I've found code online to generate the chart:

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? 

How may I move the chart within the worksheet?

回答1:

You can specify the location at the time of creation of the chart expression.AddChart(Type, Left, Top, Width, Height) see here.

If you don't want to embed the chart in a worksheet, you can create a chart sheet :

wb.Worksheets.Add(Type:=xlChart)

Caveat : Microsoft.interop.Excel not win32com, but should work.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!