自动化办公|通过xlwings进行excel格式设置

1. 介绍

xlwings 是一个强大的 Python 库,可以用来操作 Excel,包括设置单元格格式、调整行高列宽、应用条件格式以及使用内置样式。本文将详细介绍如何使用 xlwings 进行 Excel 格式化操作,并附带代码示例。

2. 基础格式设置(字体、颜色、边框)

2.1 设置字体和颜色

import xlwings as xw

wb = xw.Book('example.xlsx')
sht = wb.sheets['Sheet1']

# 设置单元格字体和颜色
rng = sht.range('A1:C3')
rng.font.name = '微软雅黑'  # 字体
rng.font.size = 12         # 字号
rng.font.color = (255, 0, 0)  # 字体颜色 (RGB)
rng.api.Font.Bold = True   # 加粗

# 设置背景色
rng.color = (255, 255, 0)  # 黄色背景

2.2 设置边框

# 设置边框
border = rng.api.Borders
border.LineStyle = 1  # 实线
border.Weight = 2     # 中等粗细
rng.api.Borders(9).LineStyle = 1  # 下边框 (9对应Excel常量xlEdgeBottom)

3. 调整行高和列宽

# 调整行高和列宽
sht.range('A1').row_height = 25    # 设置第1行高度
sht.range('A1').column_width = 15  # 设置A列宽度

# 自动调整行高列宽
sht.range('A1:C10').autofit()      # 自动调整行高和列宽
sht.autofit('columns')             # 仅自动调整列宽

4. 应用条件格式

4.1 高亮大于100的单元格

cf_range = sht.range('D1:D10')
cf = cf_range.api.FormatConditions.Add(
    Type=2,  # xlCellValue
    Operator=5,  # xlGreater
    Formula1="100"
)
cf.Font.Color = 0xFF0000  # 红色字体
cf.Interior.Color = 0xFFFF00  # 黄色背景

4.2 使用数据条(Data Bars)

cf_range.api.FormatConditions.AddDatabar()
data_bar = cf_range.api.FormatConditions(1)
data_bar.BarColor.Color = 0x00B050  # 绿色数据条

5. 使用内置样式

# 应用Excel内置样式
sht.range('A1').style = 'Good'     # 绿色背景
sht.range('B1').style = 'Bad'      # 红色背景
sht.range('C1').style = 'Neutral'  # 黄色背景

# 自定义样式
style_name = 'CustomStyle'
if style_name not in [s.Name for s in wb.api.Styles]:
    style = wb.api.Styles.Add(style_name)
    style.Font.Bold = True
    style.Interior.Color = 0x00FF00
sht.range('D1').style = style_name

6. 完整示例

import xlwings as xw

wb = xw.Book()
sht = wb.sheets[0]

# 填充测试数据
sht.range('A1').value = [[10, 200], [150, 50]]

# 格式设置
rng = sht.range('A1:B2')
rng.font.name = 'Calibri'
rng.font.size = 12
rng.column_width = 15

# 条件格式
cf = rng.api.FormatConditions.Add(
    Type=2, Operator=5, Formula1="100"
)
cf.Interior.Color = 0x00FF00

# 保存
wb.save('formatted.xlsx')
wb.close()

7. 注意事项

  • 颜色可使用 RGB 元组 (R, G, B) 或十六进制值(需转换为整数)。

  • 部分高级功能需通过 .api 调用 Excel VBA 对象模型。

相关推荐
爱丫爱1 分钟前
Python中常见库 PyTorch和Pydantic 讲解
开发语言·pytorch·python
诚信爱国敬业友善6 分钟前
GUI编程(window系统→Linux系统)
linux·python·gui
查理零世22 分钟前
【蓝桥杯集训·每日一题2025】 AcWing 6134. 哞叫时间II python
python·算法·蓝桥杯
紫雾凌寒31 分钟前
解锁机器学习核心算法|神经网络:AI 领域的 “超级引擎”
人工智能·python·神经网络·算法·机器学习·卷积神经网络
sun lover44 分钟前
conda简单命令
python·conda
Mike_188702783511 小时前
1688代采下单API接口使用指南:实现商品采集与自动化下单
前端·python·自动化
Otaku love travel1 小时前
自动化网页检测提醒
自动化·公告监测·提醒
青铜念诗1 小时前
python脚本文件设置进程优先级(在.py文件中实现)
开发语言·python
Dyan_csdn2 小时前
【Python项目】文本相似度计算系统
开发语言·python
pianmian12 小时前
python绘图之回归拟合图
开发语言·python·回归