On 08/02/2011 02:27 PM, Peter Otten wrote:
Karim wrote:
I need a generator to create the cellname in a excell (using pyuno)
document to assign value to the correct cell.
Isn't there a way to use a (row, column) tuple directly? If so I'd prefer
that. Also, there used to be an alternative format to address a spreadsheet
cell with something like "R1C2".
In fact, in pyuno I get the following code:
values = ( (22.5,21.5,121.5),
(5615.3,615.3,-615.3),
(-2315.7,315.7,415.7) )
table.getCellByName("A2").setValue(22.5)
table.getCellByName("B2").setValue(5615.3)
table.getCellByName("C2").setValue(-2315.7)
Indeed the values tuple is formated like (row, column).
I want to write simply and get cellname ondemand via an iterator
function like that:
values = ( (22.5,21.5,121.5),
(5615.3,615.3,-615.3),
(-2315.7,315.7,415.7) )
it = _xrange_cellnames(rows=len(value), cols=len(values[0]))
table.getCellByName(it.next()).setValue(22.5)
table.getCellByName(it.next()).setValue(5615.3)
table.getCellByName(it.next()).setValue(-2315.7)
The following code does this but do you have some
optimizations
on it, for instance to get the alphabetic chars instead of hard-coding it.
Cheers
karim
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def _xrange_cellnames(rows, cols):
... """Internal iterator function to compute excell table
cellnames."""
... cellnames = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
... for row in xrange(1, rows+1):
... for char in cellnames.replace('', ' ').split()[:cols]:
That is interesting ;) But for maximum clarity use
for char in cellnames[:cols]:
instead.
Yes I am blind ;o) I did not see simplification. Simple is better than
complicate...
... yield char + str(row)
...
>>> list( _xrange_cellnames(rows=3,cols=4))
['A1', 'B1', 'C1', 'D1', 'A2', 'B2', 'C2', 'D2', 'A3', 'B3', 'C3', 'D3']
Here's my (untested) attempt to handle columns beyond "Z":
from itertools import chain, count, imap, islice, product
from string import ascii_uppercase
def columnnames():
alpha = (ascii_uppercase,)
return imap("".join, chain.from_iterable(product(*alpha*i) for i in
count(1)))
def cellnames(columns, rows):
for row in xrange(1, rows+1):
for column in islice(columnnames(), columns):
yield column + str(row)
if __name__ == "__main__":
import sys
print list(cellnames(*map(int, sys.argv[1:])))
I think the subject has come up before; goo^h^h^h the search engine of your
choice is your friend.
I will study this one and itertools modules, many thanks.
Cheers
Karim
--
http://mail.python.org/mailman/listinfo/python-list