سؤال

I suspect there is an easy answer for this question but I can't find it anywhere! I am writing a function to plot a lot of data in excel and I am controlling the plotting with Python. I have generated all of the charts and each chart is its own sheet, but they are out of order. The VBA code for this is:

Sheets("Chart1").Move After:=Sheets(3)

This will take "Chart1" and move it after the 3rd sheet. How do I do this in Python? I know that the code is something along the lines of:

xlChart.Move(Before,After)

How do I tell python the Before and After parameters? I guess the big thing is I haven't figured out how to pass parameters in win32com programming.

Thanks in advance for any help!

هل كانت مفيدة؟

المحلول

Here's a very simple example:

from win32com import client

excel=client.Dispatch("Excel.Application")
excel.Visible=True
book=excel.Workbooks.Open("c:/desktop/test.xlsx", False, True)
sheet=book.Worksheets(1)
chart=book.Charts.Add()
chart.SetSourceData(sheet.Range("$A:$B"))

chart.Move(Before=book.Worksheets("Sheet2"))
chart.Move(book.Worksheets("Sheet2"))#equivalent to previous line
chart.Move(book.Worksheets("Sheet2"), None)#also equivalent

chart.Move(After=book.Worksheets("Sheet2"))
chart.Move(None,book.Worksheets("Sheet2"))#equivalent to previous line

I've tried to show the various options for dealing with optional parameters which are important issues with Excel COM programming. You can use positional parameter passing and omit parameters from the end. Or you can pass None which is equivalent. Finally, you can used named parameters.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top