openpyxl应用

本教程内容为: Python 利用 openpyxl 库操作 Excel 来实现日常办公场景的自动化(包括读写Excel,设置样式等)
本教程包含日常生活工作中的绝大多数应用场景,欢迎补充。

创建工作簿或者加载工作簿

from openpyxl import Workbook
from openpyxl import load_workbook
# 创建新的工作簿
wb = Workbook()
# 加载已有工作簿, 读取过大的excel时用read_only=True,更快写入用write_only=True
wb = load_workbook(filename='',read_only=False)
# 保存
wb.save(filename='1.xlsx')
# 关闭
wb.close()
# 另存为流
from tempfile import NamedTemporaryFile
with NamedTemporaryFile() as tmp:
    wb.save(tmp.name)
    tmp.seek(0)
    stream = tmp.read()

工作表操作

from openpyxl import Workbook
wb = Workbook()
# 获取默认活动表
ws = wb.active
# 获取指定表
ws = wb['sheet_name']
# 创建指定名称的sheet
ws = wb.create_sheet(title='sheet_name', index=0)  # index: 0  1 -1...
# 更改表名称
ws.title = 'new_sheet_name'
# 更改工作表选项卡背景色
ws.sheet_properties.tabColor = '1072BA'
# 查看所有表名称
print(wb.sheetnames)
# 单个工作簿之间创建工作表副本
ws2 = wb.copy_worksheet(ws)
# 折叠行或列
ws.row_dimensions.group(1, 10, hidden=True)
ws.column_dimensions.group('A', 'D', hidden=True)

单元格操作

from openpyxl import Workbook
wb = Workbook()
ws = wb.active
# 获取单元格
cell = ws['A2']
# 单元格赋值
cell.value = 'A2'
ws['A5'] = 5
ws.cell(row=2, column=3,value=10)
# 访问多个 cell
cell_range = ws['A1':'C4']
# 获取某行
row10 = ws[10]
# 获取某列
colC = ws['C']
# 获取多行
row_range = ws[5:10]
# 获取多列
col_range = ws['C:D']
# 按行或列遍历某个范围
for r in ws.iter_rows(min_row=1,max_row=2,min_col=1,max_col=2):
    print(r)
for c in ws.iter_cols(min_row=1,max_row=2,min_col=1,max_col=2):
    print(c)
# 遍历所有行或所有列
for r in ws.rows:
    print(r)
for r in ws.columns:
    print(r)
# 合并单元格和取消合并
ws.merge_cells('A2:E3')
ws.unmerge_cells('A2:E3')
ws.merge_cells(start_row=2, start_column=2, end_row=4, end_column=4)
ws.unmerge_cells(start_row=2, start_column=2, end_row=4, end_column=4)
# 插入和删除行或列
ws.insert_rows(idx=2, amount=1)
ws.insert_cols(idx=5, amount=1)
ws.delete_rows(idx=2, amount=1)
ws.delete_cols(idx=2, amount=1)
# 移动单元格
ws.move_range('D4:F10', rows=-1, cols=2, translate=False)
wb.close()

使用数字格式

详见下文 样式-数字格式

from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.number_dormat = 'yyyy-mm-dd h:mm:ss'
wb.close()

添加样式或注释

更多样式详见下文目录: 样式设置

from openpyxl import Workbook
from openpyxl.comments import Comment
from openpyxl.styles import Font,Alignment,Border,Side
wb = Workbook()
ws = wb.create_sheet()
cell = ws['A1']
cell.value = 10
# 设置字体
cell.font = Font(name='Courier', size=36)
# 对齐
cell.alignment = Alignment()
# 边框
cell.border = Border(left=Side(), right=Side(), top=Side(), bottom=Side())
# 添加注释
cell.comment = Comment(text='A Comment', author="Author's name")
wb.save('1.xlsx')
wb.close()

使用公式

from openpyxl import Workbook
wb = Workbook()
ws = wb.active
# 使用公式
ws['A1'] = "=SUM(1, 1)"
# 检查公式
from openpyxl.utils import FORMULAE
print('HEX2DEC' in FORMULAE)

插入图像

from openpyxl import Workbook
from openpyxl.drawing.image import Image
wb = Workbook()
ws = wb.active
ws['A1'] = 'img'
img = Image('logo.png')
ws.add_image(img, 'A1')
wb.save('1.xlsx')
wb.close()

图表

from openpyxl import Workbook
from openpyxl.chart import BarChart,Reference,Series+
wb = Workbook()
ws = wb.active
for i in range(10):
    ws.append([i])
values = Reference(ws,min_col=1, min_row=1, max_col=1, max_row=10)
chart = BarChart()
chart.add_data(values)
ws.add_chart(chart, 'E15')
wb.save('chart.xlsx')
wb.close()

样式

创建颜色

from openpyxl.styles import Color
# 使用 rgb
color = Color(rgb='00ff00', tint=0.7) 
# 使用 索引
color = Color(indexed=32)
# 使用 主题和色调
color = Color(theme=6, tint=0.5)

字体样式

from openpyxl.styles import Font, DEFAULT_FONT
# 字体
font = Font(
    name='Arial', 
    size=10,
    italic=False, # 斜体 布尔值
    bold=False, # 加粗 布尔值
    color='000000', # 可传入 rgb,亦可传入 Color对象
    strike=False, # 删除线
    underline='none', # 下划线 singleAccounting double single doubleAccounting
)

填充方式

from openpyxl.styles import PatternFill,Color
# 填充
pattern = PatternFill(
    patternType=None, 
    fgColor=Color(), 
    bgColor=Color(),
    fill_type=None,  # 填充类型:solid darkTrellis darkGrid lightHorizontal
    start_color=None,  # 填充颜色 fg_color
    end_color=None  # 填充颜色 bg_color
)

对齐方式

from openpyxl.styles import Alignment
# 对齐方式 仅需传入前两个参数
aligent = Alignment(
    horizontal='general',  # 水平 "general", "left", "center", "right", "fill", "justify", "centerContinuous", "distributed",
    vertical='center',  # 垂直 "top", "center", "bottom", "justify", "distributed"
)

边框

from openpyxl.styles import Side,Border
# 边
side = Side(
    style=None,  # 'dashDot','dashDotDot', 'dashed','dotted', 'double','hair', 'medium', 'mediumDashDot', 'mediumDashDotDot', 'mediumDashed', 'slantDashDot', 'thick', 'thin'
    border_style=None,
    color=None
)
# 单元格边框 仅需传入前四个参数
bd = Border(
        left=side,  # 左边框
        right=side,  # 右边框
        top=side,  # 顶部
        bottom=side,  # 底部
        diagonal=None,
        diagonal_direction=None,
        vertical=None,
        horizontal=None,
        diagonalUp=False,
        diagonalDown=False,
        outline=True,
        start=None,
        end=None
    )

数字格式

from openpyxl import Workbook
wb = Workbook()
ws = wb.active
# 获取单元格
cell = ws['A2']
cell.number_format = 'yyyy-mm-dd h:mm:ss'
cell.number_format = 'yyyy-mm-dd hh:mm:ss'
cell.number_format = 'yyyy年MM月dd日'
cell.number_format = '[DBNum1][$-zh-CN]上午/下午h时mm分;@'
cell.number_format = '[DBNum1][$-zh-CN]yyyy年m月d日h时mm分;@'
cell.number_format = '上午/下午h时mm分ss秒'
cell.number_format = '[$-en-US]d-mmm-yyyy;@'
cell.number_format = '[$-en-US]mmmm-yy;@'
cell.number_format = '[$-en-US]mmmmm-yy;@'
# 常见数字格式
cell.number_format = '0'
cell.number_format = '0.00'
cell.number_format = '#,##0'
cell.number_format = '#,##0.00'
cell.number_format = '0.00E+00'
cell.number_format = '# ?/?'
cell.number_format = '#,##0_);(#,##0)'
cell.number_format = '"¥"#,##0.00);("¥"#,##0.00)'
cell.number_format = '"¥"#,##0.00_);("¥"#,##0.00)'
cell.number_format = '"¥"#,##0.00_);-"¥"#,##0.00)'
cell.number_format = '$#,##0.00;-$#,##0.00'
wb.close()

其它格式

from openpyxl import Workbook
wb = Workbook()
ws = wb.active
# 获取单元格
cell = ws['A2']
# 设置列宽 A B C ...
ws.column_dimensions['A'].width = 20
# 设置行高 1 2 3 ...
ws.row_dimensions[1].width = 30
wb.close()

你可能感兴趣的:(Python,RPA,python)