3 Examples to Align Excel Text by openpyxl

The alignment of Excel cells, rows, or columns can be set by using openpyxl.styles.Alignment class.

How to align Excel text using openpyxl library

The alignment of Excel cells, rows, or columns can be set by using openpyxl.styles.Alignment class.

Following options are available to set alignment:

  • horizontal
  • indent
  • justifyLastLine
  • readingOrder
  • relativeIndent
  • shrinkToFit
  • shrink_to_fit
  • textRotation
  • text_rotation
  • vertical
  • wrapText
  • wrap_text

Each of these options has different values that you may set to align text in an Excel sheet. For example, horizontal has the following values that you may set:

  • center
  • left
  • general
  • justify
  • centerContinuous
  • right
  • fill
  • distributed

The examples below show using various options.

An example of using horizontal and vertical options

In the first example, we will use two options of the Alignment class of openpyxl:

  • horizontal
  • vertical

To show you the visual impact of different values, we will set the options of four different cells. These cells are D2 to D5.

For an idea, this is our sample sheet before applying this style:

Excel-Align-openpyxl-sample

Following is the Python code and resultant sheet after execution:

Result:

Align-horizontal-verti

You can see the difference and also notice D5 “fill” value impact.

Applying alignment style to the range of cells example

This example applies a single alignment style to a range of cells. For that, we are using a range of B4 to C8 cells.

We will apply the following options in this example:

  • horizontal=’right’
  • vertical=’center’
  • shrinkToFit=True
  • textRotation=180
  • wrapText=True

With all combined, see the sheet before (in the above example) and after the execution of this code:

Result:

Align-hor-vert-angle

The values are in this angle due to textRotation option. You may provide the angle value from 0 to 180.

Testing more options/values in the rows example

Just for diversification of our examples, we are using iter_rows function to apply alignment at row levels.

We will apply the following options and values for this example from row number 4 to the last row.

  • horizontal=’justify’
  • vertical=’top’
  • indent=100.5
  • readingOrder=2.5
  • shrinkToFit=True

In order to make rows prominent, we also highlighted them by using the background option of openpyxl:

The code:

Result:

Align-hor-vert-rows

Notice the alignment difference between the first three rows and rows 4 to 11.

 

For reference: https://openpyxl.readthedocs.io/en/latest/api/openpyxl.styles.alignment.html