当前位置:网站首页>使用openpyxl操作Excel
使用openpyxl操作Excel
2022-06-28 15:35:00 【Circle-C】
安装
pip install openpyxl
使用
# 获取范围
alphabet = '0ABCDEFGHIJKLMNOPQRSTUVWXYZ'
max_rows, max_cols = df.shape
area = f'A1:{
alphabet[max_cols]}{
max_rows + 1}'
fpath = os.path.join(path, f'Apollo对比-{
service_name}.xlsx')
df.to_excel(fpath, index=False)
# 设置样式
wb = load_workbook(fpath)
ws = wb[wb.sheetnames[0]] # 打开第一个sheet
ws.column_dimensions['A'].width = 40.0 # 调整列A宽
env_col_names = [f'{
alphabet[i]}' for i in range(1, max_cols) if ws[f'{
alphabet[i]}1'].value in env_names]
env_col_names += [f'{
alphabet[i]}' for i in range(1, max_cols) if '说明' in (ws[f'{
alphabet[i]}1'].value or '') ]
for col_name in env_col_names: # 环境key值、说明列宽
ws.column_dimensions[col_name].width = 60.0
# 条件格式
red_fill = PatternFill(bgColor="FFC7CE")
dxf = DifferentialStyle(fill=red_fill)
compare_col_names = [f'{
alphabet[i]}' for i in range(1, max_cols) if '是否一致' in (ws[f'{
alphabet[i]}1'].value or '') ]
for col_name in compare_col_names:
r = Rule(type="expression", dxf=dxf, stopIfTrue=True)
r.formula = [f'${
col_name}1="FALSE"']
ws.conditional_formatting.add(f"{
col_name}1:{
col_name}{
max_rows + 10}", r)
# 筛选
ws.auto_filter.ref = area
title_cols = ['key'] + env_names + ['环境相关']
ws.auto_filter.add_filter_column(0, title_cols)
# 冻结窗格
ws.freeze_panes = 'A2'
black_fill = PatternFill(fgColor="222222")
title_font = Font(name='Microsoft YaHei UI',
size=12,
bold=True,
italic=False,
vertAlign=None,
underline='none',
strike=False,
color='000000')
font = Font(name='Microsoft YaHei UI',
size=10,
bold=False,
italic=False,
vertAlign=None,
underline='none',
strike=False,
color='000000')
# 列的背景颜色
for i in range(2, max_rows + 2):
ws[f'A{
i}'].fill=PatternFill(fill_type='solid',fgColor="dce6f1") # key 20% blue
ws[f'{
env_col_names[0]}{
i}'].fill=PatternFill(fill_type='solid',fgColor="ebf1de") # 第一个环境名称 20% green
ws[f'{
env_col_names[-1]}{
i}'].fill=PatternFill(fill_type='solid',fgColor="fde9d9") # 说明 20% yellow
ws.cell(row=i, column=max_cols).fill=PatternFill(fill_type='solid',fgColor="e4dfec") # 环境相关 20% purple
# 边框
#定义边框样式
def my_border(t_border, b_border, l_border, r_border):
border = Border(top=Side(border_style=t_border, color=colors.BLACK),
bottom=Side(border_style=b_border, color=colors.BLACK),
left=Side(border_style=l_border, color=colors.BLACK),
right=Side(border_style=r_border, color=colors.BLACK))
return border
#初始化制定区域边框为所有框线
def format_border(area):
for row in tuple(ws[area]):
for cell in row:
cell.border = my_border('thin', 'thin', 'thin', 'thin')
format_border(area)
边栏推荐
- 利用MySqlBulkLoader实现批量插入数据的示例详解
- Fleet |「後臺探秘」第 3 期:狀態管理
- 数组中的第K大元素[堆排 + 建堆的实际时间复杂度]
- 关于针对tron API签名广播时使用curl的json解析问题解决方案及针对json.loads方法的问题记录
- C语言学习-19-全排列
- 机器学习之深度学习卷积神经网络,实现基于CNN网络的手写字体识别
- 实验6 8255并行接口实验【微机原理】【实验】
- NFT质押LP流动性挖矿系统开发详情
- MIPS assembly language learning -02- logic judgment - foreground input
- Application of mongodb in Tencent retail premium code
猜你喜欢

隆重推出 Qodana:您最爱的 CI 的代码质量平台

Visual Studio 2010 配置和使用Qt5.6.3
DBMS in Oracle_ output. put_ Line output problem solving process

Basic grammar of C language

Grand launch of qodana: your favorite CI code quality platform

Flutter simply implements multilingual internationalization
Yiwen teaches you to quickly generate MySQL database diagram

隐私计算 FATE - 离线预测

What! One command to get the surveillance?

Privacy computing fat - offline prediction
随机推荐
ROS knowledge points - build an ROS development environment using vscode
Halcon basic summary (I) cutting pictures and rotating images
不要使用短路逻辑编写 stl sorter 多条件比较
Opengauss kernel: analysis of SQL parsing process
Practice of curve replacing CEPH in Netease cloud music
R language ggplot2 visualization: use the patchwork package to stack two ggplot2 visualization results vertically to form a composite diagram, and stack one visualization result on the other visualiza
字节跳动数据平台技术揭秘:基于ClickHouse的复杂查询实现与优化
Spark SQL generate JSON
C#/VB. Net to convert PDF to excel
Oracle11g database uses expdp to back up data every week and upload it to the backup server
字节跳动数据平台技术揭秘:基于 ClickHouse 的复杂查询实现与优化
【Spock】处理 Non-ASCII characters in an identifier
Openharmony - detailed source code of Kernel Object Events
R language ggplot2 visualization: use the patchwork package (directly use the plus sign +) to horizontally combine the two ggplot2 visualization results to form a single visualization result graph
Flutter simply implements multilingual internationalization
扩充C盘(将D盘的内存分给C盘)
SAP mts/ato/mto/eto topic 9: front and back desk operation in m+m mode, strategy 50, preparation of raw materials and semi-finished products in advance
Flutter dart语言特点总结
Sample explanation of batch inserting data using MySQL bulkloader
分布式 CAP 定理的前世今生