View row values in openpyxl

大憨熊 提交于 2019-12-01 03:40:28

iter_rows() has probably a similar sense:

Returns a squared range based on the range_string parameter, using generators. If no range is passed, will iterate over all cells in the worksheet

>>> from openpyxl import load_workbook
>>> 
>>> wb = load_workbook('test.xlsx')
>>> ws = wb.get_sheet_by_name('Sheet1')
>>> 
>>> pprint(list(ws.iter_rows()))
[(<Cell Sheet1.A1>,
  <Cell Sheet1.B1>,
  <Cell Sheet1.C1>,
  <Cell Sheet1.D1>,
  <Cell Sheet1.E1>),
 (<Cell Sheet1.A2>,
  <Cell Sheet1.B2>,
  <Cell Sheet1.C2>,
  <Cell Sheet1.D2>,
  <Cell Sheet1.E2>),
 (<Cell Sheet1.A3>,
  <Cell Sheet1.B3>,
  <Cell Sheet1.C3>,
  <Cell Sheet1.D3>,
  <Cell Sheet1.E3>)]

You can modify it a little bit to yield a list of row values, for example:

def iter_rows(ws):
    for row in ws.iter_rows():
        yield [cell.value for cell in row]

Demo:

>>> pprint(list(iter_rows(ws)))
[[1.0, 1.0, 1.0, None, None],
 [2.0, 2.0, 2.0, None, None],
 [3.0, 3.0, 3.0, None, None]]
Joseph Zullo

I got it to work using this method:

all_rows = []

for row in worksheet:
    current_row = []
    for cell in row:
        current_row.append(cell.value)
    all_rows.append(current_row)

Essentially, I created a list for all of the data. Then, I iterated through each row in the worksheet. Each cell.value within a row was added to a short-term list (current row). Once all of the cell.values within the row are added to the short-term list, the short-term list is added to the long-term list.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!