对单元格进行颜色填充代码如下:
from openpyxl import Workbook
from openpyxl.styles import PatternFill
wb = Workbook()
ws = wb.active
ws['A1'].fill = PatternFill(fgColor="00C0C0C0", fill_type='solid')
wb.save('test.xlsx')
填充结果如下:A1单元格被填充为灰色。如果想要其它的颜色可以搜一下对应的十六进制颜色码。
设置Excel表格中的单元格大小(行高和列宽)
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
# 设置A列列宽为20
ws.column_dimensions['A'].width = 20.0
# 设置第一行行高为50
ws.row_dimensions[1].height = 50.0
wb.save('test.xlsx')
设置单元格字段居中
from openpyxl import Workbook
from openpyxl.styles import Alignment
wb = Workbook()
ws = wb.active
align = Alignment(horizontal='center', vertical='center', wrap_text=True)
ws['A1'] = 'test'
ws['A1'].alignment = align
wb.save('test.xlsx')
给单元格添加边框
from openpyxl.styles.borders import Border, Side
from openpyxl import Workbook
thin_border = Border(left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin'))
wb = Workbook()
ws = wb.active
# property cell.border should be used instead of cell.style.border
ws.cell(row=3, column=2).border = thin_border
wb.save('border_test.xlsx')