python使用openpyxl操作excel

目录

1 Excel表格

1.1 表格述语

1.2 表格示例

2 python打开及读取表格内容

2.1打开Excel表格并获取表格名称

2.2 通过sheet名称获取表格

2.3 获取表格的尺寸大小(几行几列数据)

2.4 获取表格内某个格子的数据

2.4.1 sheet["A1"]方式

2.4.2 sheet.cell(row=, column=)方式

2.5 获取某个格子的行数、列数、坐标

2.6 获取一系列格子

2.6.1 sheet[]方式

2.6.2 .iter_rows()方式

2.6.3 sheet.rows()

3 python向excel中写入某些内容

3.1 修改表格中的内容

3.1.1 向某个格子中写入内容并保存

3.1.2 .append():向表格中插入行数据

3.1.3 在 python 中使用 excel 函数公式

3.1.4 .insert_cols()和.insert_rows():插入空行和空列

3.1.5 .delete_rows()和.delete_cols():删除行和列

3.1.6 .move_range():移动格子

3.1.7 .create_sheet():创建新的 sheet 表格

3.1.8 .remove():删除某个 sheet 表

3.1.9 .copy_worksheet():复制一个 sheet 表到另外一张 excel 表

3.1.10 sheet.title:修改 sheet 表的名称

3.1.11 创建新的 excel 表格文件

3.1.12 sheet.freeze_panes:冻结窗口

4 批量调整字体和样式

4.1 修改字体样式

4.2 获取表格中格子的字体样式

4.3 设置对齐样式

4.4 设置边框样式

4.5 设置填充样式

4.6 设置行高和列宽

4.7 合并单元格


Excel表格

1.1 表格述语

python使用openpyxl操作excel_第1张图片

1.2 表格示例

python使用openpyxl操作excel_第2张图片

python打开及读取表格内容

2.1打开Excel表格并获取表格名称

from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
print(workbook.sheetnames)

2.2 通过sheet名称获取表格

from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook["1班"]
print(sheet)

2.3 获取表格的尺寸大小(几行几列数据)

from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook["1班"]
print(sheet.dimensions)

2.4 获取表格内某个格子的数据

2.4.1 sheet["A1"]方式

from openpyxl import load_workbook
""" 
workbook.active 打开激活的表格;
sheet["A1"] 获取 A1 格子的数据;
cell.value 获取格子中的值;
"""
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
cell1 = sheet["D2"]
cell2 = sheet["A7"]
print(cell1.value, cell2.value)

2.4.2 sheet.cell(row=, column=)方式

from openpyxl import load_workbook

workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
cell1 = sheet.cell(row = 2,column = 4)
cell2 = sheet.cell(row = 7,column = 1)
print(cell1.value, cell2.value)

2.5 获取某个格子的行数、列数、坐标

from openpyxl import load_workbook
"""
.row 获取某个格子的行数;
.columns 获取某个格子的列数;
.corordinate 获取某个格子的坐标;
"""
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
cell1 = sheet["D2"]
cell2 = sheet["A7"]
print(cell1.value, cell1.row, cell1.column, cell1.coordinate)
print(cell2.value, cell2.row, cell2.column, cell2.coordinate)

2.6 获取一系列格子

2.6.1 sheet[]方式

from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
# 获取 A2:X2 区域的值
cell = sheet["A2:X2"]
print(cell)
for i in cell:
    for j in i:
        print(j.value)

python使用openpyxl操作excel_第3张图片

特别地:如果我们只想获取“D列”,或者获取“D-F列”,可以采取如下方式:

# 获取 D 列的数据
print(sheet["D"])
# 获取 D,E,F 三列的数据
print(sheet["D:F"])
# 只获取第 5 行的数据
print(sheet[5])

2.6.2 .iter_rows()方式

.iter_rows() 方式,肯定也会有 .iter_cols() 方式,只不过一个是按行读取,一个是按列读取。
from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
# 按行获取值
for i in sheet.iter_rows(min_row=3, max_row=5, min_col=4, max_col=7):
    for j in i:
        print(j.value)
# 按列获取值
for i in sheet.iter_cols(min_row=3, max_row=5, min_col=4, max_col=7):
    for j in i:
        print(j.value)

python使用openpyxl操作excel_第4张图片

2.6.3 sheet.rows()

from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
for i in sheet.rows:
    print(i)

python使用openpyxl操作excel_第5张图片

pythonexcel中写入某些内容

3.1 修改表格中的内容

3.1.1 向某个格子中写入内容并保存

"""
注意:我们将“D2”单元格的数据改为了“总成绩”,并另存为了“new_score.xlsx”文件。 如果我们保存的时候,不修改表名,相当于直接修改源文件;
"""
from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
sheet["D2"] = "总成绩"     # 或 cell = sheet["D2"] cell.value = "总成绩"
workbook.save(filename = "new_score.xlsx")

python使用openpyxl操作excel_第6张图片

3.1.2 .append():向表格中插入行数据

.append()方式:会在表格已有的数据后面,增添这些数(按行插入)

from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
data = [
    ["14770", "张三", "高147班", "320", "70", "688"],
    ["14771", "李四", "高147班", "315", "71", "700"],
    ["14772", "王五", "高147班", "300", "72", "713"],
]
for row in data:
    sheet.append(row)
workbook.save(filename = "E:/new_score1.xlsx")

python使用openpyxl操作excel_第7张图片

3.1.3 python 中使用 excel 函数公式

from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
sheet["C3"] = "高1班"
for i in range(3,53):
    sheet["D{}".format(i)] = '=COUNTIF(D{}:D{}, ">300")'.format(i,i)
    print(sheet["D{}".format(i)])
workbook.save(filename = "E:/new_score2.xlsx")

python使用openpyxl操作excel_第8张图片

当然,我们可以使用如下操作查看一下 python支持的 “excel 函数公式 ”。
from openpyxl.utils import FORMULAE
print(FORMULAE)

3.1.4 .insert_cols().insert_rows():插入空行和空列

.insert_cols(idx= 数字编号 , amount= 要插入的列数 ) ,插入的位置是在 idx 列数的左侧插入;
.insert_rows(idx= 数字编号 , amount= 要插入的行数 ) ,插入的行数是在 idx 行数的下方插入;
 
from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
sheet.insert_cols(idx=4,amount=2)
sheet.insert_rows(idx=5,amount=4)
workbook.save(filename = "E:/new_score3.xlsx")

python使用openpyxl操作excel_第9张图片

3.1.5 .delete_rows().delete_cols():删除行和列

.delete_rows(idx= 数字编号 , amount= 要删除的行数 )
.delete_cols(idx= 数字编号 , amount= 要删除的列数 )
from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
# 删除第2列,第2行
sheet.delete_cols(idx=2)
sheet.delete_rows(idx=2)
workbook.save(filename = "E:/new_score4.xlsx")

python使用openpyxl操作excel_第10张图片

3.1.6 .move_range():移动格子

.move_range("数据区域",rows=,cols=):正整数为向下或向右、负整数为向左或向上

from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
# 向左移动一列,向下移动一行
sheet.move_range("D3:X7",rows=1,cols=-1)
workbook.save(filename = "E:/new_score5.xlsx")

3.1.7 .create_sheet():创建新的 sheet 表格

.create_sheet("新的 sheet "):创建一个新的sheet

from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
print('原:', workbook.sheetnames)
sheet = workbook.active
workbook.create_sheet("4班")
print('现:', workbook.sheetnames)
workbook.save(filename = "E:/new_score6.xlsx")

3.1.8 .remove():删除某个 sheet

from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
print('原:', workbook.sheetnames)
sheet = workbook.active
sheet = workbook['3班']
workbook.remove(sheet)
print('现:', workbook.sheetnames)
workbook.save(filename = "E:/new_score6.xlsx")

3.1.9 .copy_worksheet():复制一个 sheet 表到另外一张 excel

from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
sheet = workbook['1班']
workbook.copy_worksheet(sheet) 
workbook.save(filename = "E:/new_score7.xlsx")

 

3.1.10 sheet.title:修改 sheet 表的名称

from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
sheet.title = "147班"
print(sheet)
workbook.save(filename = "E:/new_score8.xlsx")

3.1.11 创建新的 excel 表格文件

from openpyxl import Workbook
workbook = Workbook() 
sheet = workbook.active
sheet.title = "表格 1"
workbook.save(filename = "新建的 excel 表格")

3.1.12 sheet.freeze_panes:冻结窗口

from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
sheet.freeze_panes = "B7"
workbook.save(filename = "E:/new_score9.xlsx")

批量调整字体和样式

4.1 修改字体样式

Font(name= 字体名称 ,size= 字体大小 ,bold= 是否加粗 ,italic= 是否斜体 ,color= 字体颜色 )
from openpyxl.styles import Font
from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
cell = sheet["A1"] 
font = Font(name="微软雅黑",size=20,bold=True,italic=True,color="FF0000")
cell.font = font
workbook.save(filename = "E:/new_score11.xlsx")

python使用openpyxl操作excel_第11张图片

4.2 获取表格中格子的字体样式

from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
cell = sheet["A2"]
font = cell.font
print(font.name, font.size, font.bold, font.italic, font.color)

4.3 设置对齐样式

Alignment(horizontal= 水平对齐模式 ,vertical= 垂直对齐模式 ,text_rotation= 旋转角度,wrap_text= 是否自动换行 )
水平对齐: ‘distributed' ‘justify' ‘center' ‘leftfill' ‘centerContinuous' ‘right ,‘general';
垂直对齐: ‘bottom' ‘distributed' ‘justify' ‘center' ‘top'
from openpyxl.styles import Alignment
from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
cell = sheet["A1"]
alignment = Alignment(horizontal="center",vertical="center",text_rotation=45,wrap_text=True)
cell.alignment = alignment
workbook.save(filename = "E:/new_score13.xlsx")
python使用openpyxl操作excel_第12张图片

 

4.4 设置边框样式

Side(style= 边线样式, color= 边线颜色 )
Border(left= 左边线样式, right= 右边线样式, top= 上边线样式, bottom= 下边线样式 )
style 参数的种类: 'double, 'mediumDashDotDot', 'slantDashDot', 'dashDotDot','dotted','hair','mediumDashed, 'dashed', 'dashDot', 'thin', 'mediumDashDot','medium', 'thick'
from openpyxl.styles import Side,Border
from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
cell = sheet["D6"]
side1 = Side(style="thin",color="FF0000")
side2 = Side(style="thick",color="FFFF0000")
border = Border(left=side1,right=side1,top=side2,bottom=side2)
cell.border = border
workbook.save(filename = "E:/new_score14.xlsx")

4.5 设置填充样式

PatternFill(fill_type= 填充样式, fgColor= 填充颜色)
GradientFill(stop=( 渐变颜色 1 ,渐变颜色 2……))
from openpyxl.styles import PatternFill,GradientFill
from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
cell_b9 = sheet["D3"]
pattern_fill = PatternFill(fill_type="solid",fgColor="99ccff")
cell_b9.fill = pattern_fill
cell_b10 = sheet["D5"]
gradient_fill = GradientFill(stop=("FFFFFF","99ccff","000000"))
cell_b10.fill = gradient_fill
workbook.save(filename = "E:/new_score15.xlsx")

4.6 设置行高和列宽

.row_dimensions[ 行编号 ].height = 行高
.column_dimensions[ 列编号 ].width = 列宽
from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
# 设置第 1 行的高度
sheet.row_dimensions[1].height = 50
# 设置 B 列的宽度
sheet.column_dimensions["B"].width = 20
workbook.save(filename = "E:/new_score16.xlsx")

python使用openpyxl操作excel_第13张图片

4.7 合并单元格

.merge_cells( 待合并的格子编号 )
.merge_cells(start_row= 起始行号, start_column= 起始列号, end_row= 结束行号,end_column=结束列号 )
from openpyxl import load_workbook
workbook = load_workbook(filename = 'E:/score.xlsx')
sheet = workbook.active
sheet.merge_cells("A3:B53")
# 或 sheet.merge_cells(start_row=7,start_column=1,end_row=8,end_column=3)
workbook.save(filename = "E:/new_score17.xlsx")
python使用openpyxl操作excel_第14张图片

 

你可能感兴趣的:(Python,python,pycharm,openpyxl,excel)