How to Add Border in Excel (Cell, Range, Rows) by openpyxl

By using openpyxl library, you may add borders to the Excel cells. Not only it enables you to add a border of the same style but you may specify different border styles for each side of the cell.

Adding borders in Excel sheet by openpyxl

By using openpyxl library, you may add borders to the Excel cells.

Not only it enables you to add a border of the same style but you may specify different border styles for each side of the cell.

Following border styles are available:

  • dashed
  • dotted
  • double
  • thick
  • thin
  • dashDot
  • dashDotDot
  • medium
  • mediumDashDot
  • mediumDashDotDot
  • mediumDashed
  • hair

See examples below of setting single and different borders for individual cells. Later, you can also see examples of setting single and multiple rows borders.

An example of setting cells border of the same type

In this example, we will set the border of a cell of the same type. We will use the following sample sheet for all our examples below:

Excel-border-sample

You can see, the Status column cells are without any border. We will set the double border for two cells with the value “In Stock” (green color) and two cells of thick type (in red) with the value “Out of Stock”:

Python program:

Resultant sheet:

Excel-Border-openpyxl

Setting border style and color of each side of Excel range example

In this example, we set the border and colors of each side (left, right, top, and bottom) and assign them to the range of cells in the Excel sheet.

For that, we used the following border types:

  • top=dashDotDot
  • left=mediumDashDot
  • right=slantDashDot
  • bottom=thin

We assigned this from C4 to D8 range of cells as shown in the program below:

The code:

Result:

Border-openpyxl-range

Applying border to rows example

In this example, we will apply border style to an unknown number of rows. We only know where to start applying border and we will get the last row number and apply various border styles to each side of the cell.

Have a look at the example and result sheet:

Result:

Border-openpyxl-rows