gpt4 book ai didi

python - 在openpyxl中查看行值

转载 作者:太空狗 更新时间:2023-10-29 18:28:46 25 4
gpt4 key购买 nike

在 python 的 csv 模块中,有一个名为 csv.reader 的函数,它允许您遍历一行,返回一个 reader 对象,并且可以像列表一样保存在容器中。

所以当列表赋值给一个变量并被打印时,即:

csv_rows = list(csv.reader(csvfile, delimiter=',', quotechar='|'))
print (csv_rows)
>
>
>
[['First Name', 'Last Name', 'Zodicac', 'Date of birth', 'Sex'] # I gave an example of the function outputting a header row

到目前为止,我在 openpyxl 中没有看到类似的功能。我可能弄错了,所以我想知道是否有人可以帮助我。

更新

@alecxe,您的解决方案非常有效(除了将我的出生日期转换为日期时间格式而不是常规字符串)。

def iter_rows(ws):
for row in ws.iter_rows():
yield [cell.value for cell in row]
>
>
>>> pprint(list(iter_rows(ws)))
[['First Nam', 'Last Name', 'Zodicac', 'Date of birth', 'Sex'], ['John', 'Smith', 'Snake', datetime.datetime(1989, 9, 4, 0, 0), 'M']]

因为我是初学者,所以我想知道如果我使用 for 循环而不是列表推导式会如何工作。

所以我用了这个:

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

几乎 给了我完全相同的输出,而是给了我这个:如您所知,它实际上给了我一个巨大的列表,而不是您给我的结果中的嵌套列表。

>>>print(list(iter_rows(ws)))

[['First Nam', 'Last Name', 'Zodicac', 'Date of birth', 'Sex', 'David', 'Yao', 'Snake', datetime.datetime(1989, 9, 4, 0, 0), 'M']]

最佳答案

iter_rows()可能有类似的意义:

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>)]

您可以稍微修改它以生成行值列表,例如:

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

演示:

>>> 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]]

关于python - 在openpyxl中查看行值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31236998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com