python怎么将表格样式一起写入新表格
时间: 2024-05-13 20:17:56 浏览: 91
python实现数据写入excel表格
你可以使用 `openpyxl.styles` 模块来实现将表格样式一起写入新表格。以下是一个简单的示例代码:
```python
from openpyxl import Workbook
from openpyxl.styles import Font, Color, PatternFill, Alignment, Border, Side
# 创建一个新的工作簿
wb = Workbook()
# 选择活动工作表
ws = wb.active
# 为单元格创建样式
font_style = Font(name='Arial', size=12, bold=True, color='FFFFFF')
fill_style = PatternFill(start_color='0066CC', end_color='0066CC', fill_type='solid')
align_style = Alignment(horizontal='center', vertical='center')
border_style = 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'))
# 写入数据到单元格,同时应用样式
ws['A1'] = '姓名'
ws['A1'].font = font_style
ws['A1'].fill = fill_style
ws['A1'].alignment = align_style
ws['A1'].border = border_style
ws['B1'] = '年龄'
ws['B1'].font = font_style
ws['B1'].fill = fill_style
ws['B1'].alignment = align_style
ws['B1'].border = border_style
ws['C1'] = '性别'
ws['C1'].font = font_style
ws['C1'].fill = fill_style
ws['C1'].alignment = align_style
ws['C1'].border = border_style
# 保存工作簿
wb.save('my_excel_file.xlsx')
```
以上代码示例创建一个新的 Excel 表格,并向其添加三列数据(姓名、年龄和性别),同时将单元格的字体、背景颜色、对齐方式和边框设置为特定的样式。最后,将工作簿保存到名为 `my_excel_file.xlsx` 的文件中。你可以根据自己的需求修改代码并添加更多的样式。
阅读全文