openpyxl设置单元格格式
时间: 2024-10-14 19:04:32 浏览: 62
在使用OpenPyXL库处理Excel文件时,你可以通过`openpyxl.styles`模块来设置单元格的格式。以下是设置常见单元格格式的基本步骤:
1. 导入所需的样式模块:
```python
from openpyxl.styles import Font, Alignment, PatternFill, Border, Color, NamedStyle
```
2. 设置字体、对齐、填充、边框等样式:
```python
# 设置字体样式
font_style = Font(name='Arial', size=12, bold=True, italic=False)
# 设置对齐样式
alignment_style = Alignment(horizontal='center', vertical='top')
# 设置填充样式(例如,红色背景)
fill_style = PatternFill(start_color='FF0000', end_color='FF0000', fill_type='solid')
# 设置边框样式
border_style = Border(left=BorderWeight.THIN, right=BorderWeight.THIN, top=BorderWeight.THIN, bottom=BorderWeight.THIN)
```
3. 应用到单元格上:
```python
# 获取工作表和单元格引用
sheet = workbook['Sheet1']
cell = sheet['A1']
# 给单元格应用样式
cell.font = font_style
cell.alignment = alignment_style
cell.fill = fill_style
cell.border = border_style
```
4. 如果需要创建自定义命名样式,可以这样做:
```python
custom_style = NamedStyle(name='Custom Style')
custom_style.font = font_style
custom_style.alignment = alignment_style
custom_style.fill = fill_style
custom_style.border = border_style
workbook.add_named_style(custom_style)
```
阅读全文