from openpyxl import load_workbook
wb = load_workbook('C:/Users/Administrator/Desktop/test.xlsx')
# 獲得所有sheet的名稱
print(wb.get_sheet_names())
# 根據(jù)sheet名字獲得sheet
a_sheet = wb.get_sheet_by_name('Sheet1')
# 獲得sheet名
print(a_sheet.title) #Sheet1
# 獲得當(dāng)前正在顯示的sheet, 也可以用wb.get_active_sheet()
sheet = wb.active
print('當(dāng)前正在顯示的sheet---', sheet)
? ?
? ? #獲得excel表格對象
? ? sheet1=wb[Sheet1]
print(sheet1)#<Worksheet "Sheet1">
#獲取生成器對象
print(sheet.values)#<generator object Worksheet.values at 0x00000248E4E3ABA0>
? ? #將生成器轉(zhuǎn)化為列表
? ? print(list(sheet.values))#[('姓名', '性別'), ('張三', '男'), ('李四', '女')]
獲取最大行和最大列
# 獲取最大行和最大列
print('最大行數(shù)---', a_sheet.max_row)
print('最大列數(shù)---', a_sheet.max_column)
最大行數(shù)--- 3
最大列數(shù)--- 2
獲取某個(gè)單元格的值
# 獲取某個(gè)單元格的值
b2 = a_sheet['B2']
print('B2是----', b2) # 返回的數(shù)字就是int型
print(f'({b2.column}, {b2.row}) 處的值為: {b2.value}') # 返回的數(shù)字就是int型
B2是---- <Cell 'Sheet1'.B2>
(2, 2) 處的值為: 男
獲取行和列文章來源:http://www.zghlxwxcb.cn/news/detail-614240.html
# 獲取行和列
row3 = [item.value for item in list(a_sheet.rows)[1]]
print('第2行值', row3)
col2 = [item.value for item in list(a_sheet.columns)[1]]
print('第2列值', col2)
通過worksheet.cell獲取所有數(shù)據(jù)方法文章來源地址http://www.zghlxwxcb.cn/news/detail-614240.html
print('通過worksheet.cell獲取所有數(shù)據(jù)方法:')
for i in range(1, a_sheet.max_row+1):
for j in range(1, a_sheet.max_column+1):
print(a_sheet.cell(row=i, column=j).value,end=' ')
print('\n')
通過worksheet.cell獲取所有數(shù)據(jù)方法:
姓名 性別
張三 男
李四 女
到了這里,關(guān)于python之使用openpyxl讀取excel的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!