Python格式化excel表格样式
时间: 2023-05-24 20:03:06 浏览: 98
python操作excel表格 格式设置
A:可以使用openpyxl模块来格式化excel表格样式。
首先导入openpyxl模块:
```python
import openpyxl
from openpyxl.styles import Font, Color, Alignment, PatternFill, Border, Side
from openpyxl.utils import get_column_letter
```
接着打开excel文件并选择对应的表格:
```python
workbook = openpyxl.load_workbook('example.xlsx')
worksheet = workbook['Sheet1']
```
通过设置单元格的属性,可以改变字体、颜色、对齐方式和填充等样式。例如,要将第一行的字体设置为粗体,颜色设置为红色,对齐方式设置为居中:
```python
for col in range(1, worksheet.max_column + 1):
cell = worksheet.cell(row=1, column=col)
cell.value = cell.value.title()
cell.font = Font(bold=True, color='FF0000')
cell.alignment = Alignment(horizontal='center', vertical='center')
```
以上代码将第一行的单元格属性依次设置为粗体、红色、居中对齐。
要给单元格填充颜色,可以使用PatternFill类。例如,要将第一列的所有单元格背景设置为浅灰色:
```python
greyFill = PatternFill(start_color='C0C0C0', end_color='C0C0C0', fill_type='solid')
for row in range(2, worksheet.max_row + 1):
cell = worksheet.cell(row=row, column=1)
cell.fill = greyFill
```
以上代码将第一列的所有单元格背景设置为浅灰色。
最后保存文件:
```python
workbook.save('formatted_example.xlsx')
```
完整代码:
```python
import openpyxl
from openpyxl.styles import Font, Color, Alignment, PatternFill, Border, Side
from openpyxl.utils import get_column_letter
workbook = openpyxl.load_workbook('example.xlsx')
worksheet = workbook['Sheet1']
# 格式化第一行
for col in range(1, worksheet.max_column + 1):
cell = worksheet.cell(row=1, column=col)
cell.value = cell.value.title()
cell.font = Font(bold=True, color='FF0000')
cell.alignment = Alignment(horizontal='center', vertical='center')
# 格式化第一列
greyFill = PatternFill(start_color='C0C0C0', end_color='C0C0C0', fill_type='solid')
for row in range(2, worksheet.max_row + 1):
cell = worksheet.cell(row=row, column=1)
cell.fill = greyFill
workbook.save('formatted_example.xlsx')
```
阅读全文