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 对象模型。