当前位置:网站首页>使用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)
边栏推荐
- R语言ggplot2可视化:使用patchwork包(直接使用加号+)将一个ggplot2可视化结果和数据表格横向组合起来形成最终结果图
- What! 一条命令搞定监控?
- ROS21讲
- CODING DevOps 助力中化信息打造新一代研效平台,驱动“线上中化”新未来
- Qt5.5.1配置MSVC2010编绎器和windbg调试器
- [leetcode] 13. Roman numeral to integer
- R language ggplot2 visualization: the patchwork package horizontally combines a ggplot2 visualization result and a plot function visualization result to form a final result graph, aligns the two visua
- In depth learning foundation summary
- 分布式 CAP 定理的前世今生
- Experiment 6 8255 parallel interface experiment [microcomputer principle] [experiment]
猜你喜欢

Web3.0时代来了,看天翼云存储资源盘活系统如何赋能新基建(上)

Soliciting articles and contributions - building a blog environment with a lightweight application server

部门新来了个字节25K出来的,让我见识到了什么是天花板

What! 一条命令搞定监控?

Privacy computing fat - offline prediction

扩充C盘(将D盘的内存分给C盘)

Halcon basic summary (I) cutting pictures and rotating images

Opengauss kernel: analysis of SQL parsing process

【LeetCode】13、罗马数字转整数

NAACL 2022 | 机器翻译SOTA模型的蒸馏
随机推荐
Flutter simply implements multilingual internationalization
R language uses the multinom function of NNET package to build an unordered multi classification logistic regression model, and uses regression coefficients and their standard errors to calculate the
Grand launch of qodana: your favorite CI code quality platform
Experiment 6 8255 parallel interface experiment [microcomputer principle] [experiment]
ORACLE中dbms_output.put_line输出问题的解决过程
Technical secrets of ByteDance data platform: implementation and optimization of complex query based on Clickhouse
Leike defense: 4D millimeter wave radar products are expected to be mass produced and supplied by the end of the year
MIPS assembly language learning-01-sum of two numbers, environment configuration and how to run
See how the interface control devaxpress WinForms creates a virtual keyboard
The best time to buy and sell stocks
sql语句 练习题
R语言ggplot2可视化:patchwork包将一个ggplot2可视化结果和一个plot函数可视化结果横向组合起来形成最终结果图、两个可视化的组合结果对齐、并为组合图像的每个子图添加标题
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
10:00面试,10:02就出来了 ,问的实在是太...
Qt5.5.1配置MSVC2010编绎器和windbg调试器
What! 一条命令搞定监控?
一文教你快速生成MySQL数据库关系图
The past and present life of distributed cap theorem
Facebook! Adaptive gradient defeats manual parameter adjustment
Express template engine