1、基本概念
在openpyxl中,主要用到三个概念:Workbooks,Sheets,Cells。
Workbook就是一个excel工作表;
Sheet是工作表中的一张表页;
Cell就是简单的一个格。
openpyxl就是围绕着这三个概念进行的,不管读写都是“三板斧”:
打开Workbook,定位Sheet,操作Cell。
下面分读和写分别介绍几个常见的方法。
1.1 打开 Excel 表格并获取表格名称
from openpyxl import load_workbook
workbook = load_workbook(filename ="test.xlsx")
workbook.sheetnames
1.2 通过 sheet 名称获取表格
from openpyxl import load_workbook
workbook = load_workbook(filename ="test.xlsx")
workbook.sheetnames
sheet = workbook["Sheet1"]
print(sheet)
1.3 获取表格的尺寸大小 几行几列数据
sheet.dimensions
1.4 获取表格内某个格子的数据
workbook = load_workbook(filename ="test.xlsx")
sheet = workbook.active
print(sheet)
cell1 = sheet["A1"]
cell2 = sheet["C11"]
print(cell1.value, cell2.value)
workbook = load_workbook(filename ="test.xlsx")
sheet = workbook.active
print(sheet)
cell1 = sheet.cell(row = 1,column = 1)
cell2 = sheet.cell(row = 11,column = 3)
print(cell1.value, cell2.value)
1.5 获取某个格子的行数、列数、坐标
workbook = load_workbook(filename ="test.xlsx")
sheet = workbook.active
print(sheet)
cell1 = sheet["A1"]
cell2 = sheet["C11"]
print(cell1.value, cell1.row, cell1.column,cell1.coordinate)
print(cell2.value, cell2.row, cell2.column,cell2.coordinate)
1.6 获取一系列格子
workbook = load_workbook(filename ="test.xlsx")
sheet = workbook.active
print(sheet)
# 获取A1:C2区域的值
cell = sheet["A1:C2"]
print(cell)
for i in cell:
for j in i:
print(j.value)
sheet["A"] --- 获取A列的数据
sheet["A:C"] --- 获取A,B,C三列的数据
sheet[5] --- 只获取第5行的数据
1.7 按行获取值
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)
1.8 按列获取值
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)
1.9 向某个格子中写入内容并保存
workbook = load_workbook(filename ="test.xlsx")
sheet = workbook.active
print(sheet)
sheet["A1"] = "哈喽"
# 这句代码也可以改为cell =sheet["A1"] cell.value ="哈喽"
workbook.save(filename = "哈喽.xlsx")
1.10 向表格中插入行数据
workbook = load_workbook(filename ="test.xlsx")
sheet = workbook.active
print(sheet)
data = [ ["唐僧","男","180cm"], ["孙悟空","男","188cm"], ["猪八戒","男","175cm"], ["沙僧","男","176cm"], ]
for row in data:
sheet.append(row)
workbook.save(filename ="test.xlsx")
1.11 在 python 中使用 excel 函数公式
workbook = load_workbook(filename ="test.xlsx")
sheet = workbook.active
print(sheet)
sheet["D1"] = "标准身高"
for i in range(2,16):
sheet["D{}".format(i)]= '=IF(RIGHT(C{},2)="cm",C{},SUBSTITUTE(C{},"m","")*100&"cm")'.format(i,i,i)
workbook.save(filename ="test.xlsx")
1.12 其他命令
.insert_rowss() 和.insert_ cols():插入空行和空列
.delete_rows() 和.delete_ cols():删除行和列
.move_ range():移动格子
.create_ sheet():创建新的 sheet 表格
. remove():删除某个sheet 表
.copy_ worksheet():复制一个 sheet 表到另外一张 excel 表
sheet.title :修改sheet 表的名称