在上面例子的基础上再加上标题居中, 加粗,并且所有单元格加上边框,请给出完整实例
时间: 2023-09-06 08:11:28 浏览: 73
jquery 实例完整例子
好的,以下是一个完整的示例代码,实现了标题居中、加粗和单元格边框的要求:
```python
from openpyxl import Workbook
from openpyxl.styles import Alignment, Font, Border, Side
# 创建工作簿和活动表
wb = Workbook()
ws = wb.active
# 设置标题
ws.merge_cells('A1:C1')
ws['A1'] = '学生成绩单'
ws['A1'].alignment = Alignment(horizontal='center')
ws['A1'].font = Font(bold=True)
# 设置表头
ws['A2'] = '姓名'
ws['B2'] = '语文'
ws['C2'] = '数学'
# 设置单元格边框
border = Border(left=Side(border_style='thin'),
right=Side(border_style='thin'),
top=Side(border_style='thin'),
bottom=Side(border_style='thin'))
for row in ws.iter_rows(min_row=2, max_row=2):
for cell in row:
cell.border = border
# 设置学生成绩
ws['A3'] = '张三'
ws['B3'] = 90
ws['C3'] = 80
ws['A4'] = '李四'
ws['B4'] = 85
ws['C4'] = 92
ws['A5'] = '王五'
ws['B5'] = 88
ws['C5'] = 87
# 设置单元格边框
for row in ws.iter_rows(min_row=3, max_row=5):
for cell in row:
cell.border = border
# 保存文件
wb.save('example.xlsx')
```
在上面的代码中,我们首先使用 `ws.merge_cells('A1:C1')` 将 A1 到 C1 的单元格合并成一个单元格,然后使用 `ws['A1'].alignment` 和 `ws['A1'].font` 分别设置居中和加粗样式。接着,我们设置了表头和学生成绩,并使用循环为表头和学生成绩的单元格设置了边框样式。最后,我们使用 `wb.save()` 将工作簿保存到本地。
阅读全文