Python设置excel单元格样式
时间: 2023-07-07 07:04:54 浏览: 123
使用Python的openpyxl库可以设置Excel单元格样式,具体步骤如下:
1. 导入openpyxl库和相关模块
```python
from openpyxl import Workbook
from openpyxl.styles import Font, Color, Alignment, PatternFill
from openpyxl.utils import get_column_letter
```
2. 创建一个Workbook对象
```python
wb = Workbook()
```
3. 获取活动工作表
```python
ws = wb.active
```
4. 设置单元格样式
例如,设置A1单元格为红色、加粗、斜体、水平居中、垂直居中,背景填充为黄色:
```python
# 设置字体
font = Font(color='FF0000', bold=True, italic=True)
ws['A1'].font = font
# 设置对齐方式
alignment = Alignment(horizontal='center', vertical='center')
ws['A1'].alignment = alignment
# 设置背景填充
fill = PatternFill(start_color='FFFF00', end_color='FFFF00', fill_type='solid')
ws['A1'].fill = fill
```
5. 保存Excel文件
```python
wb.save('example.xlsx')
```
完整代码示例:
```python
from openpyxl import Workbook
from openpyxl.styles import Font, Color, Alignment, PatternFill
from openpyxl.utils import get_column_letter
wb = Workbook()
ws = wb.active
# 设置字体
font = Font(color='FF0000', bold=True, italic=True)
ws['A1'].font = font
# 设置对齐方式
alignment = Alignment(horizontal='center', vertical='center')
ws['A1'].alignment = alignment
# 设置背景填充
fill = PatternFill(start_color='FFFF00', end_color='FFFF00', fill_type='solid')
ws['A1'].fill = fill
# 保存Excel文件
wb.save('example.xlsx')
```
阅读全文