pythonexcelmacosapplescriptpy-appscript

python appscript for macOS


I am trying to use python package appscript to control applications in my MacBook. Unfortunately I am really confused.

For example, I am trying to control one of my excel files. I want to get the position and scroll to certain roll. Here is my code

# -*- coding:utf-8 -*-

from appscript import *

file = app('Microsoft Excel').documents[u'test.csv']
position = file.window.left_position()
print position

The code is only trying to get the position but it is not working. I download the ASDictionary to check the command but I still can not fix it. Here is the screenshot of the command:

enter image description here

Thank you so much for your help.


Solution

  • Excel’s Apple event (“AppleScript”) support is atypical and quirky.

    1. Avoid using documents; it doesn’t work correctly. Use workbooks instead.

    2. Workbooks don’t have a window property. They do, however, have windows elements (since you can view a workbook in more than one window).

    Corrected Python code:

    wb = app('Microsoft Excel').workbooks[u'test.csv']
    position = wb.windows[1].left_position()
    print(position)
    

    Or, in AppleScript:

    tell application "Microsoft Excel"
        tell workbook "test.csv"
            get left position of window 1
        end tell
    end tell