views:

164

answers:

1

How do I access the current table in Numbers using py-appscript?


For posterity, the program I created using this information clears all the cells of the current table and returns the selection to cell A1. I turned it into a Service using a python Run Shell Script in Automator and attached it to Numbers.

 from appscript import *

 Numbers = app('Numbers')
 current_table = None
 for sheet in Numbers.documents.first.sheets():
      for table in sheet.tables():
           if table.selection_range():
                current_table = table

 if current_table:
      for cell in current_table.cells():
           cell.value.set('')

      current_table.selection_range.set(to=current_table.ranges[u'A1'])

It was used to clear large tables of numbers that I used for temporary calculations.

+2  A: 
>>> d = app('Numbers').documents.first()  # reference to current top document

EDIT: There doesn't seem to be a straight-forward single reference to the current table but it looks like you can find it by searching the current first document's sheets for a table with a non-null selection_range, so something like this:

>>> nu = app('Numbers')
>>> for sheet in nu.documents.first.sheets():
...   for table in sheet.tables():
...     if table.selection_range():
...        print table.name()
Ned Deily
This actually isn't working for me. It returns the first table in the sheet, not the currently selected table.
Chris Redford
Ironically, I *just* came to this conclusion myself and was about to post it :) The syntax in your solution is cleaner, though.
Chris Redford
Heh. The wonders of Apple Event scriptable apps: seek and ye shall find. And there is seldom the one obvious way to do it.
Ned Deily
Thanks for your help. I've got another question on appscript that I'm hoping you have the answer to.
Chris Redford