pandas 设置excel表格样式
时间: 2023-04-24 21:00:22 浏览: 1255
Pandas表格样式设置指南
5星 · 资源好评率100%
Pandas可以使用openpyxl库来设置Excel表格样式。具体步骤如下:
1. 导入openpyxl库和pandas库
```python
import openpyxl
import pandas as pd
```
2. 读取Excel文件
```python
df = pd.read_excel('example.xlsx')
```
3. 创建ExcelWriter对象
```python
writer = pd.ExcelWriter('example.xlsx', engine='openpyxl')
```
4. 将DataFrame写入Excel文件
```python
df.to_excel(writer, sheet_name='Sheet1', index=False)
```
5. 获取工作簿和工作表对象
```python
workbook = writer.book
worksheet = writer.sheets['Sheet1']
```
6. 设置单元格样式
```python
from openpyxl.styles import Font, Color, Alignment, Border, Side, colors
# 设置字体
font = Font(name='Calibri', size=12, bold=True, italic=False, color=colors.BLACK)
# 设置背景颜色
fill = PatternFill(start_color='FFC7CE', end_color='FFC7CE', fill_type='solid')
# 设置边框
border = Border(left=Side(border_style='thin', color='000000'),
right=Side(border_style='thin', color='000000'),
top=Side(border_style='thin', color='000000'),
bottom=Side(border_style='thin', color='000000'))
# 设置对齐方式
alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
# 设置单元格样式
cell_format = NamedStyle(name='cell_format')
cell_format.font = font
cell_format.fill = fill
cell_format.border = border
cell_format.alignment = alignment
workbook.add_named_style(cell_format)
# 设置单元格样式
for row in range(2, worksheet.max_row + 1):
for col in range(1, worksheet.max_column + 1):
cell = worksheet.cell(row=row, column=col)
cell.style = cell_format
```
7. 保存Excel文件
```python
writer.save()
```
以上就是使用Pandas设置Excel表格样式的步骤。
阅读全文