簡體   English   中英

從 openpyxl 循環行獲取單元格數據

[英]Getting cell data from openpyxl looped rows

我有一些代碼可以在 python 腳本中從 OpenPyXL 創建元組,如下所示:

for row in sheet.iter_rows(min_row=2, max_col=2, max_row=50)
    print(row)

哪個返回

(<Cell 'States'.A2>, <Cell 'States'.B2>)
(<Cell 'States'.A3>, <Cell 'States'.B3>)
...
(<Cell 'States'.A50>, <Cell 'States'.B50>)

我想通過使用 cell.value 並通過逗號分隔值(例如 7,100 或 100,7)進一步拆分“B 列”從“A 列”和“B 列”中提取值將值添加到如下所示的字典中:

StatesPriority = {
    A2 : (B2.ValueBeforeComma, B2.ValueAfterComma)
    A3 : (B3.ValueBeforeComma, B3.ValueAfterComma)
    ...
    A50 : (B50.ValueBeforeComma, B50.ValueAfterComma)
}

但是,我更關心從返回的元組中獲取值的 OpenPyXL function。 我想我可以花一點時間自己找出用逗號分隔的值。

Python 版本:3.6.3 OpenPyXL 版本:2.4.9

感謝所有幫助!

row是一個包含兩個元素的元組,因此您可以在賦值期間解壓縮它:

StatesPriority = {}
for row in sheet.iter_rows(min_row=2, max_col=2, max_row=50)
    cell_a, cell_b = row
    StatesPriority[cell_a.value] = (tuple(cell_b.value.split(','))

經過一番研究,我相信新方法是使用values_only=True ,如下所示:

for row in sheet.iter_rows(min_row=2, max_col=2, max_row=50, values_only=True)
    print(row)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM