openpyxl指定单元格样式
时间: 2024-09-26 09:01:59 浏览: 34
python-openpyxl读写Excel
在`openpyxl`库中,你可以通过`Workbook`或`Sheet`对象来操作Excel工作表并设置单元格的样式。以下是如何指定单元格样式的步骤:
1. 首先,你需要导入`openpyxl`模块以及`styles`模块,它包含了各种样式定义:
```python
from openpyxl import Workbook
from openpyxl.styles import Font, Color, PatternFill, Alignment, Border, Side
```
2. 创建或打开一个工作簿,并选择你想操作的工作表:
```python
wb = Workbook()
ws = wb.active
```
3. 使用`Font`、`Color`、`PatternFill`等来定义样式。例如,设置字体颜色和大小:
```python
font = Font(color='FF0000', size=16) # 红色大字
```
4. 设置单元格的内容及其样式:
```python
cell = ws['A1']
cell.value = 'Hello'
cell.font = font
```
5. 对于复杂的样式,如填充颜色、边框、对齐方式等,可以组合使用`Alignment`, `Border`, 和`Side`对象:
```python
alignment = Alignment(horizontal='center', vertical='top')
border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin'))
filled_cell = cell.fill = PatternFill(start_color='FFFF00', end_color='FFFF00', fill_type='solid') # 黄色填充
cell.alignment = alignment
cell.border = border
```
阅读全文