1. 介紹
xlwings
是一個強大的 Python 庫,可以用來操作 Excel,包括設置單元格格式、調整行高列寬、應用條件格式以及使用內置樣式。本文將詳細介紹如何使用 xlwings
進行 Excel 格式化操作,并附帶代碼示例。
2. 基礎格式設置(字體、顏色、邊框)
2.1 設置字體和顏色
import xlwings as xwwb = 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, # xlCellValueOperator=5, # xlGreaterFormula1="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 = Truestyle.Interior.Color = 0x00FF00
sht.range('D1').style = style_name
6. 完整示例
import xlwings as xwwb = 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 對象模型。