How To Expande and Shrink Specified Regions Using OpenPyXL?

Method

  • Expand using the `expand` method of the `CellRange` object

cr.expand(right=0,down=0,left=0,up=0)

  • using the `shrink` method of the `CellRange` object

cr.shrink(right=0,bottom=0,left=0,top=0)

 

Use the `size` attribute to view the changes before and after.

Sample Code

#Expanding and Shinking Cell Ranges

#Import load_workbook function
from openpyxl import Workbook

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

#Import CellRange function
from openpyxl.worksheet.cell_range import CellRange

#Create a cell range object
cr=CellRange('D5:F7')
#Output the size of the cell range
print(cr.size)

#Expanding
cr.expand(right=1,down=2,left=0,up=0)
print(cr.size)
#Shinking
#cr.shrink(right=1,bottom=2,left=0,top=0)
#print(cr.size)

wb.save('test.xlsx')
wb.close()
Expande and Shrink Specified Regions Using OpenPyXL

How To Move Cell Ranges Using OpenPyXL?

Method

Move a range using the `move_range` method of the worksheet object:

ws.move_range(cr,rows,cols)

The first parameter of this method specifies the range to be moved, which must be a CellRange object; the rows parameter defines the vertical movement. If the value is greater than 0, it moves down; if the value is less than 0, it moves up. The cols parameter defines the horizontal movement. If the value is greater than 0, it moves to the right; if the value is less than 0, it moves to the left.

Sample Code

#Move the Cell Range

#Import load_workbook function
from openpyxl import Workbook

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

#Move the cell range
#Row: >0 moves down; <0 moves up
#Column: >0 moves right; <0 moves left

from openpyxl.styles import PatternFill
ws['D4'].fill=PatternFill(fill_type='solid', start_color='00FF00')
ws['F10'].fill=PatternFill(fill_type='solid', start_color='00FF00')
ws.move_range('D4:F10', rows=-1, cols=2)

wb.save('test.xlsx')
wb.close()
Move Cell Ranges Using OpenPyXL

How To Copy Cell Range Styles Using OpenPyXL?

Method

Copying styles:

from copy import copy

cr=CellRange(‘D5:F7’)

cr2=CellRange(‘D12:F14’)

r=cr2.max_row-cr.max_row

c=cr2.max_col-cr.max_col

for cl in cr.cells:

      cl2=ws.cell(row=cl[0],column=cl[1])

      ws.cell(row=cl[0]+r,column=cl[1]+c,value=cl2.value)

      if cl2.has_style:

            nc=ws.cell(row=cl[0]+r,column=cl[1]+c)

            nc.font=copy(cl2.font)

            nc.border=copy(cl2.border)

            nc.fill=copy(cl2.fill)

            nc.number_format=copy(cl2.number_format)

            nc.alignment=copy(cl2.alignment)

Sample Code

#Copy the Style of a Cell Range

#Import load_workbook function
from openpyxl import Workbook

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

#Import CellRange class and copy function
from openpyxl.worksheet.cell_range import CellRange
from copy import copy

#Create two cell ranges
cr=CellRange('D5:F7')
cr2=CellRange('D12:F14')

#Copy the style
r=cr2.max_row-cr.max_row
c=cr2.max_col-cr.max_col
for cl in cr.cells:
      cl2=ws.cell(row=cl[0],column=cl[1])
      ws.cell(row=cl[0]+r,column=cl[1]+c,value=cl2.value)
      #If there are styles, use the `copy` function to copy them
      if cl2.has_style:
            nc=ws.cell(row=cl[0]+r,column=cl[1]+c)
            nc.font=copy(cl2.font)
            nc.border=copy(cl2.border)
            nc.fill=copy(cl2.fill)
            nc.number_format=copy(cl2.number_format)
            nc.alignment=copy(cl2.alignment)

wb.save('test.xlsx')
wb.close()

How To Copy Cell Ranges Using OpenPyXL?

Method

Copying content:

from openpyxl.worksheet.cell_range import CellRange

cr=CellRange(‘D5:F7’)

cr2=CellRange(‘D12:F14’)

r=cr2.max_row-cr.max_row

c=cr2.max_col-cr.max_col

for cl in cr.cells:

      cl2=ws.cell(row=cl[0],column=cl[1])

      ws.cell(row=cl[0]+r,column=cl[1]+c,value=cl2.value)

Sample Code

#Copy Cell Ranges

#Import load_workbook function
from openpyxl import Workbook

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

#Import CellRange class
from openpyxl.worksheet.cell_range import CellRange

#Create a cell range object
cr=CellRange('D5:F7')
cr2=CellRange('D12:F14')

#Copy the values
r=cr2.max_row-cr.max_row
c=cr2.max_col-cr.max_col
for cl in cr.cells:
      cl2=ws.cell(row=cl[0],column=cl[1])
      ws.cell(row=cl[0]+r,column=cl[1]+c,value=cl2.value)

wb.save('test.xlsx')
wb.close()

How To Set Cell Styles Using OpenPyX – Protection

Method

from openpyxl.styles import Protection

 

#Set protection

ws[‘C3’].protection=Protection(locked=True)

ws[‘C3′]=’abc123’

ws.protection.sheet=True

Sample Code

#Cell Style: Setting Protection

#Import load_workbook function
from openpyxl import Workbook

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

#Import Protection class
from openpyxl.styles import Protection

#Set protection
ws['C3'].protection=Protection(locked=False)
ws['C3']='abc123'
ws.protection.sheet=True

wb.save('test.xlsx')
wb.close()

How To Set Cell Styles Using OpenPyX – Alignment

Method

Use the `Alignment` class constructor to create an `Alignment` object, which you can use to set the alignment of data in a cell.

from openpyxl.styles.alignment import Alignment

Alignment(horizontal=None, vertical=None, textRotation=0, wrapText=None, shrinkToFit=None, indent=0, relativeIndent=0, justifyLastLine=None, readingOrder=0, text_rotation=None, wrap_text=None, shrink_to_fit=None, mergeCell=None)

Where

  • horizontal—Horizontal alignment, which must be one of: “general”“center”“justify”“distributed”“fill”“right”“centerContinuous”“left”
  • vertical—Vertical alignment, which must be one of: “bottom”“distributed”“justify”“center”“top”
  • textRotation—The text rotation angle in degrees. Its value must be one of the following.

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180

  • wrapText—Whether text wrapping is allowed (Boolean).
  • shrinkToFit—Whether to shrink the text to fit the cell.
  • indent—The indent level, a floating-point number.
  • relativeIndent—The relative indent level, a floating-point number.
  • justifyLastLine—Whether to justify the last line (Boolean).
  • readingOrder—The reading order, a floating-point number.
  • text_rotation—An alias for **textRotation**, used when the property name is invalid, conflicts with a Python keyword, or is more descriptive.
  • wrap_text—An alias for wrapText
  • shrink_to_fit—An alias for shrinkToFit
  • mergeCell—Merges the cell.

Sample Code

#Cell Style: Set the Alignment

#Import load_workbook function
from openpyxl import Workbook

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

#Import the Alignment class
from openpyxl.styles import Alignment

#Set the alignment
align1=Alignment(horizontal='center', vertical='top')
align2=Alignment(horizontal='right', vertical='bottom', \
                 text_rotation=30, wrap_text=True, \
                 shrink_to_fit=True, indent=0)
align3=Alignment(horizontal='center', vertical='center', \
                 wrap_text=True, indent=3)

#Apply the first alignment style to cell C2
ws['C2'].alignment=align1
ws['C2'].value='Python123'

#Apply the second alignment style to cell C4
ws['C4'].alignment=align2
ws['C4'].value='Python123'

#Apply the third alignment style to cell C6
ws['C6'].alignment=align3
ws['C6'].value='Python123'

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

How To Set Cell Styles Using OpenPyX – Number Format

Method

Use the `numbers` module and the `number_format` property of the cell object to set number formats.

>>> from openpyxl.styles import numbers

There are two ways to set the number format:

1. Using the built-in constants of OpenPyXl:

>> ws[“D2”].number_format=numbers.FORMAT_GENERAL

2. Using a string representation of the number format:

>> ws[“D6″].number_format=”yy-mm-dd”

>> ws[“D8″].number_format=”d-mmm-yy”

To display numbers in scientific notation:

>> ws[“D4”].number_format = ‘0.00E+00’

 

The available format constants and strings in OpenPyXl are as follows:

  • FORMAT_GENERAL=”General”
  • FORMAT_TEXT=”@”
  • FORMAT_NUMBER=”0″
  • FORMAT_NUMBER_00=”0.00″
  • FORMAT_NUMBER_COMMA_SEPARATED1=”#,##0.00″
  • FORMAT_NUMBER_COMMA_SEPARATED2=”#,##0.00_-“
  • FORMAT_PERCENTAGE=”0%”
  • FORMAT_PERCENTAGE_00=”0.00%”
  • FORMAT_DATE_YYYYMMDD2=”yyyy-mm-dd”
  • FORMAT_DATE_YYMMDD=”yy-mm-dd”
  • FORMAT_DATE_DDMMYY=”dd/mm/yy”
  • FORMAT_DATE_DMYSLASH=”d/m/y”
  • ……

Sample Code

#Cell Style: Setting Number Formats

#Import load_workbook function
from openpyxl import Workbook

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

#Import numbers class
from openpyxl.styles import numbers
import datetime

#Set the number format
ws['D2']='Test123'
ws['D6']=datetime.datetime.today()
ws['D8']=datetime.datetime.today()
ws['D4']=123.456789
ws['D2'].number_format=numbers.FORMAT_GENERAL
ws['D6'].number_format='yy-mm-dd'
ws['D8'].number_format='d-mmm-yy'
ws['D4'].number_format='0.00E+00'

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

How To Set Cell Styles Using OpenPyX – Border

Method

Use the `Border` class to create a border object and apply it to a cell.

from openpyxl.styles.borders import Border,Side

Border(left=<openpyxl.styles.borders.Side object> Parameters: style=None, color=None, right=<openpyxl.styles.borders.Side object> Parameters: style=None, color=None, top=<openpyxl.styles.borders.Side object> Parameters: style=None, color=None, bottom= <openpyxl.styles.borders.Side object>

Parameters: style=None, color=None, diagonal=<openpyxl.styles.borders. Side object> Parameters: style=None, color=None, diagonal_direction=None, vertical=None, horizontal=None, diagonalUp=False, diagonalDown=False, outline= True, start=None, end=None)

Where

  • leftrighttopbottomdiagonalDefine the left, right, top, bottom, and diagonal borders, as **Side** objects.
  • diagonalDowndiagonalUpBoolean values, define the direction of the diagonal line. It can be drawn from the top-left to bottom-right, or from the bottom-left to top-right.

A Side object represents a border, which is a line-shaped graphical element. Its main properties include the line style and color. The constructor for this Side object is as follows:

Side(style=None, color=None, border_style=None)

Where

  • styleThe border style, which must be one of: “hair”“dashed”“mediumDashDot”“mediumDashDotDot”“slantDashDot”“double”“thick”“mediumDashed”“thin”“medium”“dashDotDot”“dashDot”“dotted”
  • colorThe color of the border.
  • border_styleAn alias for style.

Sample Code

#Cell Style: Setting Borders

#Import load_workbook function
from openpyxl import Workbook

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

#Import Border class and Side class
from openpyxl.styles import Border, Side

#Set cell borders
#Use the Border function to create individual borders
ws.cell(row=4, column=4).border = Border(left=Side(border_style='thin', \
            color='FF0000'), right=Side(border_style='thin', \
            color='FF0000'), top=Side(border_style='double', \
            color='FF0000'), bottom=Side(border_style='double', \
            color='FF0000'))

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

How To Set Cell Styles Using OpenPyX – Background Pattern Fill

Method

You can set cell background fill using either gradient fill or pattern fill, using the `GradientFill` and `PatternFill` classes respectively.

  • Pattern Fill

Use the `PatternFill` class to create a pattern fill object.

from openpyxl.styles.fills import PatternFill

PatternFill(patternType=None,fgColor=<openpyxl.styles.colors.Color object>

Parameters: rgb=’00000000′, indexed=None, auto=None, theme=None, tint=0.0, type=’rgb’, bgColor=<openpyxl. styles.colors.Color object>

Parameters: rgb=’00000000′, indexed=None, auto=None, theme=None, tint=0.0, type=’rgb’, fill_type=None, start_color=None, end_color= None)

Where

patternTypefill_typeThe pattern fill type, its value must be one of the following: “darkDown”“gray0625”“mediumGray”“darkHorizontal”“lightVertical”“darkGrid”“lightGray”“darkTrellis”“darkVertical”“lightGrid”“solid”“lightDown”“lightUp”“darkUp”“darkGray”“lightTrellis”“lightHorizontal”“gray125”None

fgColorstart_colorForeground color, the value of fgColor must be a Color object.

bgColorend_colorBackground color, the value of bgColor must be a Color object.

 

When **fill_type** is set to None, no fill will be applied.

When **fill_type** is set to ‘Solid’, it will be a solid color fill.

Sample Code

#Cell Style: Pattern Fill

#Import load_workbook function
from openpyxl import Workbook

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

#Import PatternFill class
from openpyxl.styles import PatternFill
from openpyxl.styles.colors import Color

#Pattern fill
ws['B2'].fill=PatternFill(fill_type=None, \
            start_color='FFFF00', end_color='000000')
ws['C2'].fill=PatternFill(fill_type='solid', \
            start_color='00FF00')
ws['E2'].fill=PatternFill(fill_type='lightGrid', \
            start_color='FFFF00', end_color='000000')
fill=PatternFill(fill_type='lightTrellis', \
            fgColor=Color(rgb='00FF00'), bgColor=Color(rgb='0000FF'))
ws.column_dimensions['B'].fill=fill
fill=PatternFill(fill_type='lightGray', \
            fgColor=Color(rgb='FFFF00'), bgColor=Color(rgb='0000FF'))
ws.row_dimensions[4].fill = fill

wb.save('test.xlsx')
wb.close()
Set Cell Styles Using OpenPyX - Background Pattern Fill

How To Set Cell Styles Using OpenPyX – Background Gradient Fill

Method

You can set cell background fill using either gradient fill or pattern fill, using the `GradientFill` and `PatternFill` classes respectively.

  • Gradient Fill

Use the `GradientFill` class to create a gradient fill object and apply it to the cell.

from openpyxl.styles.fills import GradientFill,Stop

GradientFill(type=’linear’, degree=0, left=0, right= 0, top=0,bottom=0, stop=())

type:  ‘linear’ for linear gradient, ‘path’ for path gradient.

degree: From 0 to 360, with 0 degrees being horizontal to the right, rotating clockwise.

Stop(‘FF0000’,0.5)

stop1=(‘FF0000′,’00FF00′,’0000FF’)    #Equal intervals

stop2=(Stop(‘FF0000’,0.0),Stop(‘FF0000’,0.3),Stop(‘FF0000’,1.0))    #Unequal intervals

cl_1.fill=GradientFill(type=’linear’, stop=stop1)

cl_2.fill=GradientFill(type=’linear’, stop=stop2)

cl_3.fill=GradientFill(type=’linear’, degree=45,stop=stop1)

cl_4.fill=GradientFill(type=’path’, left=0.5, right= 0.5, top=0.5,bottom=0.5, stop=stop1)

Sample Code

#Cell Style: Gradient Fill

#Import load_workbook function
from openpyxl import Workbook

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

#Import GradientFill class
from openpyxl.styles import GradientFill
#Apply gradient color fill to cells
#Linear gradient: gradient from one side of the cell to the other
#Path gradient: gradient from the four edges of the cell inward
ws['B2'].fill=GradientFill(type='linear', \
        degree=0, left=0, right=0, top=0, bottom=0, \
        stop=['FF0000','0000FF'])
ws['E2'].fill=GradientFill(type='linear', \
        degree=45, left=0, right=0, top=0, bottom=0, \
        stop=['FF0000','0000FF'])
ws['G2'].fill = GradientFill(type='path', \
        left=0.2, right=0.8, top=0.3, bottom=0.7, \
        stop=['FF0000','0000FF'])
ws.row_dimensions[4].fill=GradientFill(type='linear', \
        degree=0, left=0, right=0, top=0, bottom=0, \
        stop=['FF0000','00FF00'])

wb.save('test.xlsx')
wb.close()
Set Cell Styles Using OpenPyX - Background Gradient Fill