读sheet
from openpyxl import load_workbook
wb = load_workbook("files/p1.xlsx")
# sheet相关操作
# 1.获取excel文件中的所有sheet名称
"""
print(wb.sheetnames) # ['数据导出', '用户列表', 'Sheet1', 'Sheet2']
"""
# 2.选择sheet,基于sheet名称
"""
sheet = wb["数据导出"]
cell = sheet.cell(1, 2)
print(cell.value)
"""
# 3.选择sheet,基于索引位置
"""
sheet = wb.worksheets[0]
cell = sheet.cell(1,2)
print(cell.value)
"""
# 4.循环所有的sheet
"""
for name in wb.sheetnames:
sheet = wb[name]
cell = sheet.cell(1, 1)
print(cell.value)
"""
"""
for sheet in wb.worksheets:
cell = sheet.cell(1, 1)
print(cell.value)
"""
"""
for sheet in wb:
cell = sheet.cell(1, 1)
print(cell.value)
"""
读sheet中单元格的数据
from openpyxl import load_workbook
wb = load_workbook("files/p1.xlsx")
sheet = wb.worksheets[0]
# 1.获取第N行第N列的单元格(位置是从1开始)
"""
cell = sheet.cell(1, 1)
print(cell.value)
print(cell.style)
print(cell.font)
print(cell.alignment)
"""
# 2.获取某个单元格
"""
c1 = sheet["A2"]
print(c1.value)
c2 = sheet['D4']
print(c2.value)
"""
# 3.第N行所有的单元格
"""
for cell in sheet[1]:
print(cell.value)
"""
# 4.所有行的数据(获取某一列数据)
"""
for row in sheet.rows:
print(row[0].value, row[1].value)
"""
# 5.获取所有列的数据
"""
for col in sheet.columns:
print(col[1].value)
"""
读合并的单元格
from openpyxl import load_workbook
wb = load_workbook("files/p1.xlsx")
sheet = wb.worksheets[2]
# 获取第N行第N列的单元格(位置是从1开始)
c1 = sheet.cell(1, 1)
print(c1) # <Cell 'Sheet1'.A1>
print(c1.value) # 用户信息
c2 = sheet.cell(1, 2)
print(c2) # <MergedCell 'Sheet1'.B1>
print(c2.value) # None
from openpyxl import load_workbook
wb = load_workbook('files/p1.xlsx')
sheet = wb.worksheets[2]
for row in sheet.rows:
print(row)
>>> 输出结果
(<Cell 'Sheet1'.A1>, <MergedCell 'Sheet1'.B1>, <Cell 'Sheet1'.C1>)
(<Cell 'Sheet1'.A2>, <Cell 'Sheet1'.B2>, <Cell 'Sheet1'.C2>)
(<Cell 'Sheet1'.A3>, <Cell 'Sheet1'.B3>, <Cell 'Sheet1'.C3>)
(<MergedCell 'Sheet1'.A4>, <Cell 'Sheet1'.B4>, <Cell 'Sheet1'.C4>)
(<Cell 'Sheet1'.A5>, <Cell 'Sheet1'.B5>, <Cell 'Sheet1'.C5>)