python如何獲取多個excel單元格的值

2022-03-11 07:38:34 字數 2590 閱讀 7721

需要讀取的sample.xlsx

**讀取的是a3:b10之間的單元格

from openpyxl import

load_workbook

wb = load_workbook(r"

d:\python_workshop\python6\study\sample.xlsx")

sh = wb["

sheet"]

print(sh["

a3":"

b10"

].value)

執行結果:

traceback (most recent call last):

file

"d:/python_workshop/python6/study/demo.py

", line 8, in

print(sh["

a3":"

b10"

].value)

attributeerror:

'tuple' object has no attribute 'value'

上面報錯資訊是,元組物件沒有屬性"value",我們先來看一下print(sh["a2":"b10"]),得到的是乙個元組,比較有意思的是,元組中的每一項也是乙個元組,這個元組裡儲存的是每一行的單元格物件:相當於 元組(a3: b10) ——> 第三行:元組(a3: b3),第四行:元組(a4: b4)...第十行:元組(a10: b10)——>每乙個單元格物件

print(sh["

a3":"

b10"

])執行結果:(('

sheet

'.a3>, '

sheet

'.b3>), ('

sheet

'.a4>, '

sheet

'.b4>), ('

sheet

'.a5>, '

sheet

'.b5>), ('

sheet

'.a6>, '

sheet

'.b6>), ('

sheet

'.a7>, '

sheet

'.b7>), ('

sheet

'.a8>, '

sheet

'.b8>), ('

sheet

'.a9>, '

sheet

'.b9>), ('

sheet

'.a10>, '

sheet

'.b10>))

這種多層巢狀的形式,我們要想獲得最裡面單元格物件,就要用到雙層for迴圈:

for item in sh["

a3":"

b10"]: #

item表示每一行的單元格元組

for cell in item: #

cell表示每一行的每乙個單元格物件

print(cell) #

列印出每個單元格物件

執行結果:

'sheet

'.a3>

'sheet

'.b3>

'sheet

'.a4>

'sheet

'.b4>

'sheet

'.a5>

'sheet

'.b5>

'sheet

'.a6>

'sheet

'.b6>

'sheet

'.a7>

'sheet

'.b7>

'sheet

'.a8>

'sheet

'.b8>

'sheet

'.a9>

'sheet

'.b9>

'sheet

'.a10>

'sheet

'.b10>

得到單元格物件就好辦了,只需要單元格物件.value,我們就可以獲取單元格值。試試按照excel中的形式列印,得到的結果看起來很美觀:

#

用enumerate包裝乙個可迭代物件,可以同時使用索引和迭代項,在迭代的同時獲取迭代項所在位置時非常方便

for index, item in enumerate(sh["

a3":"

b10"

]):

if index > 0:

print("\n"

)

for cell in

item:

print(cell.value, end="")

執行結果:

2018-05-10電影

hello world **

hi 資料

stop 美團

bike 花生

中國 電視

測試 連續劇

深圳 廣告

python基礎(六)python操作excel

一 python操作excel,python操作excel使用xlrd xlwt和xlutils模組,xlrd模組是讀取excel的,xlwt模組是寫excel的,xlutils是用來修改excel的。這幾個模組使用pip安裝即可,下面是這幾個模組的使用。二 xlrd模組,xlrd模組用來讀exce...

react路由如何傳遞多個引數,並獲取多個引數

應用場景 需要傳遞多個引數,但是只在url中顯示其中乙個,其他引數在props中獲取 使用函式元件hooks 使用js新增到路由 props.history.push 在元件中獲取引數 hooks元件router獲取引數有四個常用方法 useparams,uselocation,usehistory...

npoi獲取合併單元格 NPOI操作EXCEL

年專案有乙個子模組需要解析上百張不一樣的excel 入庫,當時用的npoi,做了很久.也嘗試想把 分享到oschina,結果沒堅持兩篇就放棄了。趕巧的是,昨天運營那邊提出要錄入一些基礎資料,我想著也就幾百個員工 企業的資訊,自己找兩個姑娘手動錄入唄 為啥是姑娘?讓乙個大老爺們去錄假資料,你去嗎?反正...