使用openpyxl把表格的表头设计成浅蓝色,全部表格加边框,输出到EXCEL
时间: 2024-04-29 17:26:07 浏览: 200
中怎么做?
你可以使用 openpyxl 库来操作 Excel 表格。首先,要导入 openpyxl 模块并打开一个 Excel 文件:
```python
from openpyxl import Workbook
from openpyxl.styles import Border, Side, PatternFill, Font, Alignment
wb = Workbook()
ws = wb.active
```
然后,你可以设置表头的样式为浅蓝色:
```python
header_fill = PatternFill(start_color='9BC2E6', end_color='9BC2E6', fill_type='solid')
header_font = Font(bold=True, color='FFFFFF')
for col in range(ws.min_column, ws.max_column + 1):
cell = ws.cell(row=1, column=col)
cell.fill = header_fill
cell.font = header_font
```
接下来,你可以给表格添加边框。定义四条边的样式:
```python
thin = Side(border_style="thin", color="000000")
border = Border(
left=thin,
right=thin,
top=thin,
bottom=thin
)
```
然后,遍历表格的每个单元格,给它们添加边框样式:
```python
for row in ws.iter_rows():
for cell in row:
cell.border = border
```
最后,将表格保存到 Excel 文件:
```python
wb.save('example.xlsx')
```
这样就完成了表格样式的设计和输出到 Excel 文件中。
阅读全文