③ 在python中使用excel函数公式(很有用)
# 这是我们在excel中输入的公式 =IF(RIGHT(C2,2)="cm",C2,SUBSTITUTE(C2,"m","")*100&"cm") # 那么,在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")
结果如下:
此时,你肯定会好奇,python究竟支持写哪些“excel函数公式”呢?我们可以使用如下操作查看一下。
import openpyxl from openpyxl.utils import FORMULAE print(FORMULAE)
结果如下:
④ .insert_cols()和.insert_rows():插入空行和空列
.insert_cols(idx=数字编号, amount=要插入的列数),插入的位置是在idx列数的左侧插入;
.insert_rows(idx=数字编号, amount=要插入的行数),插入的行数是在idx行数的下方插入;
workbook = load_workbook(filename = "test.xlsx") sheet = workbook.active print(sheet) sheet.insert_cols(idx=4,amount=2) sheet.insert_rows(idx=5,amount=4) workbook.save(filename = "test.xlsx")
结果如下:
⑤ .delete_rows()和.delete_cols():删除行和列
.delete_rows(idx=数字编号, amount=要删除的行数)
.delete_cols(idx=数字编号, amount=要删除的列数)
workbook = load_workbook(filename = "test.xlsx") sheet = workbook.active print(sheet) # 删除第一列,第一行 sheet.delete_cols(idx=1) sheet.delete_rows(idx=1) workbook.save(filename = "test.xlsx")
结果如下:
⑥ .move_range():移动格子
.move_range(“数据区域”,rows=,cols=):正整数为向下或向右、负整数为向左或向上;
# 向左移动两列,向下移动两行 sheet.move_range("C1:D4",rows=2,cols=-1)
演示效果如下:
⑦ .create_sheet():创建新的sheet表格
.create_sheet(“新的sheet名”):创建一个新的sheet表;
workbook = load_workbook(filename = "test.xlsx") sheet = workbook.active print(sheet) workbook.create_sheet("我是一个新的sheet") print(workbook.sheetnames) workbook.save(filename = "test.xlsx")
结果如下:
⑧ .remove():删除某个sheet表
.remove(“sheet名”):删除某个sheet表;
workbook = load_workbook(filename = "test.xlsx") sheet = workbook.active print(workbook.sheetnames) # 这个相当于激活的这个sheet表,激活状态下,才可以操作; sheet = workbook['我是一个新的sheet'] print(sheet) workbook.remove(sheet) print(workbook.sheetnames) workbook.save(filename = "test.xlsx")
结果如下: