使用openpyxl操作excel(一)
1、打开excel表格并获取表格名称
from openpyxl import load_workbook
workbook = load_workbook(filename="test.xlsx")
print(workbook.sheetnames)
#输出 ['Sheet1', 'Sheet2', 'Sheet3']
2、通过sheet名称获取表格
from openpyxl import load_workbook
workbook = load_workbook(filename="test.xlsx")
sheet = workbook["Sheet1"]
print(sheet)
#输出 <Worksheet "Sheet1">
3、获取表格的尺寸大小(几行几列数据)
from openpyxl import load_workbook
workbook = load_workbook(filename="test.xlsx")
sheet = workbook["Sheet1"]
print(sheet.dimensions)
#输出 'A1:H11'
4、获取表格内某个格子的数据
4.1 sheet["A1"]方式
from openpyxl import load_workbook
workbook = load_workbook(filename="test.xlsx")
sheet = workbook.active #打开激活的表格
cell1 = sheet["A1"] #获取A1格子的数据
print(cell1.value) #获取格子中的值
#输出 1
4.2 sheet.cell(row=,column=)
from openpyxl import load_workbook
workbook = load_workbook(filename="test.xlsx")
sheet = workbook.active #打开激活的表格
cell1 = sheet.cell(row = 1,column = 1) #获取A1格子的数据
print(cell1.value) #获取格子中的值
5、获取某个格子的行数、列数、坐标
from openpyxl import load_workbook
workbook = load_workbook(filename="test.xlsx")
sheet = workbook.active #打开激活的表格
cell1 = sheet["A1"] #获取A1格子的数据
print(cell1.value,cell1.row,cell1.column,cell1.coordinate)
# 输出1,1,A,A1
# .row 获取某个格子的行数,.columns 获取某个格子的列数,.corordinate 获取某个格子的坐标
6、获取一系列格子
6.1 sheet[]方式
from openpyxl import load_workbook
workbook = load_workbook(filename="test.xlsx")
sheet = workbook.active #打开激活的表格
cell1 = sheet["A1:C2"]
for i in cell:
for j in i:
print(j.value)
# 注意:格子中的数据,是按行读取的
6.2 .iter_rows()方式
from openpyxl import load_workbook
workbook = load_workbook(filename="test.xlsx")
sheet = workbook.active
# 按行获取值
for i in sheet.iter_rows(min_row=2,max_row=5,min_col=1,max_col=2):
for j in i:
print(j.value)
# 按列获取值
for i in sheet.iter_cols(min_row=2,max_row=5,min_col=1,max_col=2):
for j in i:
print(j.value)
6.3 sheet.rows()
# 帮助我们获取所有行
from openpyxl import load_workbook
workbook = load_workbook(filename="test.xlsx")
sheet = workbook.active
for i in sheet.rows:
print(i)