如何使用 OpenPyXL 从返回的元组中获取值

How to get values from a returned tuple using OpenPyXL

我编写了一些代码,使用 OpenPyXL 库从 .xlsx 文件中迭代列生成元组。

from openpyxl import workbook
wb = load_workbook('....\example.xlsx')
ws = wb.get_sheet_by_name('SomeMatrix')
c = tuple(ws.columns)
print c

哪个returns

((<Cell u'SomeMatrix'.A1>, <Cell u'SomeMatrix'.B1>, ..., <Cell u'SomeMatrix'.CY1>),...
,(<Cell u'SomeMatrix'.A400>, <Cell u'SomeMatrix'.B400>, <Cell u'SomeMatrix'.CY400>))

我想从这些多列中提取值(例如,通过使用 cell.value),这样我就可以获得一个名为 c 的元组元组,它应该如下所示:

c= ((1,2,...,1234),(3,5,...,9328),...,(2,1,...,4321))

对于遇到类似问题的任何人,我最终是如何解决的。 请注意,我是 Python 编码的新手,所以我不能保证这是一个有效的解决方案。如果我的陈述有误,请纠正我。另外,欢迎 post 更短 and/or 更高效的解决方案。

使用 iter_cols() 函数 returns 生成器,它可以快速处理单次迭代,因为它不会在访问数据之前将数据加载到内存中。相反,它会即时访问所有内容。

我的代码现在看起来像这样:

from openpyxl import workbook
wb = load_workbook('Path\to\Matrix.xlsx')
ws = wb.get_sheet_by_name('SomeMatrix')

def iter_cols(ws):                               #define your own iter_cols function which yields the cell values via for loop
  for col in ws.iter_cols():
     yield tuple(cell.value for cell in col)     #the yield statement returns a generator
c = tuple(iter_cols(ws))