How To Set Cell Styles Using OpenPyX – Overview

Method

Import related classes to set the cell style. OpenPyXl  has six related classes:

  • NumberFormat
  • Font
  • Alignment
  • PatternFill
  • Border
  • Protection

Import them before using them:

from openpyxl.styles import numbers,Font, Alignment

from openpyxl.styles import PatternFill, Border, Side, Protection

Sample Code

#Working with Cell Styles

#Import load_workbook function
from openpyxl import Workbook

#Create a new workbook
wb=Workbook()
#Get the active worksheet
ws=wb.active

#Import cell style-related classes
from openpyxl.styles import numbers,Font,Alignment
from openpyxl.styles import PatternFill,Border,Side,Protection
from openpyxl.styles import Font

#Create fonts
font=Font(bold=True)

#Get a cell
cl=ws['C3']

#Set the font of a cell
cl.font=font

#Set the font of a cell range
for row in ws['A1:C3']:
    for cell in row:
        cell.font = font

#Set the font of a row
row=ws.row_dimensions[1]
row.font=font

#Set the font of a column
column=ws.column_dimensions['A']
column.font=font

wb.save('test.xlsx')
wb.close()
Set Cell Styles Using OpenPyX

Leave a Reply

Your email address will not be published. Required fields are marked *