2015-07-13 46 views
1

我正在使用Openpyxl。我也願意接受使用其他方法/模塊的答案。引用同一行中的單元格

所以引用單元格值,你可以這樣做:

ws = wb.get_active_sheet() 
for cellobject in sheet.columns[1]: 
    print(cellobject.value) 


1001 
1002 
1003 
1004 

但如果我想引用單元格在同一行,例如列C(有點像一個VLOOKUP公式)?

| A   | B   | 
|:-----------|------------:| 
| 1001  | Cow  |  
| 1002  | Cat  |  
| 1003  | Dog  |   
| 1004  | Mouse  | 

所以,最終的結果可能是這個樣子:

(1001, Cow) 
(1002, Cat) 

或:

1001 
Cow 
1002 
Cat 

回答

1

只是通過第一和第二列壓縮功能。

for cellobject1, cellobject2 in zip(sheet.columns[1], sheet.columns[1]): 
    print((cellobject1.value, cellobject2.value)) 
2

您也可以嘗試去在ws.rows,這會給你的每一行(完整的所有列)一個接一個,例如 -

for row in ws.rows: 
    print((row[0].value, row[1].value)) #for first and second column. 

,或者您可以通過行迭代以及,以獲得行中的每個單元格。示例 -

for row in ws.rows: 
    for cell in row: 
     print(cell.value) #this will print cell by cell , in a new line. 
相關問題