Am .05.2016, 21:12 Uhr, schrieb <
msch...@mrn.org>:
Hiya Megan,
> Hi Charlie, Thanks for your help!
>
> It turns out that my "successful" column grab also fails, as I was just
> investigating its contents and finding it also had the wrong index the
> way I was doing it. I understand now the difference between cell
> indexing and the other tuples' indices.
>
> How would you suggest searching over the whole spreadsheet, as I look for
> my needed columns? Here is what I have, and I'm not sure how to use the
> sheet.columns[-1] syntax to build a range:
Is this a continuation of your Stackoverflow question?
The "best", or at least the most flexible way to search an Excel sheet is
probably to build a dictionary of the values, though this may be
unsuitable for large files.
from collections import defaultdict
words = defaultdict(list)
for row in ws.iter_rows():
for cell in row:
if cell.data_type == 's':
words[cell.value].append((cell.row, cell.column)) # the numerical
col_idx is also available or you could just enumerate()
So, say you have "cat" in B2 and E45:
words["cat"] == [(2, B), (45, E)] # I hope
> for column in range(1, sheet.max_column+1 ):
> for row in range(1, 5): # headers are only in the first few rows
> matchObj = re.search('target header', str(sheet.cell(row= row,
> column= column).value))
> if matchObj :
> target_column = column
> # I would change sheet.columns[target_column] to
> useful_column = sheet.columns[target_column - 1]
You should try and avoid creating your own ranges and use properties
provided as it's much easier to read and your using tested™ code.
I'm not quite sure what you're looking for but the following should help
you get along
for row in ws.iter_rows('A1', row_offset=4, column_offset=ws.max_column-1):
for cell in row:
m = re.search(regex, cell.value)
if m:
return ws.columns[cell.col_idx - 1]
Version 2.4 improves the handling here a bit by letting you pass in
min_row, min_column, max_row and max_column and also gives you
ws.iter_cols() to work with so that if you are working with columns you
can break out of the inner loop.
Hope that helps a bit.