Apply 'wrap_text' to all cells using openpyxl

DerRabe picture DerRabe · Feb 14, 2017 · Viewed 20.5k times · Source

I have a Pandas dataframe that I am writing out to an XLSX using openpyxl. Many of the cells in the spreadsheet contain long sentences, and i want to set 'wrap_text' on all the contents of the sheet (i.e. every cell).

Is there a way to do this? I have seen openpyxl has an 'Alignment' option for 'wrap_text', but I cannot see how to apply this to all cells.

Edit:

Thanks to feedback, the following does the trick. Note - copy due to styles being immutable.

for row in ws.iter_rows():
    for cell in row:      
        cell.alignment =  cell.alignment.copy(wrapText=True)

Answer

SuperNova picture SuperNova · Sep 25, 2018

I have been using openpyxl>=2.5.6. Let us say we want to wrap text for cell A1, then we can use the below code.

from openpyxl.styles import Alignment

ws['A1'].alignment = Alignment(wrap_text=True)