27

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)
DerRabe
  • 313
  • 1
  • 3
  • 6

5 Answers5

41

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)
SuperNova
  • 25,512
  • 7
  • 93
  • 64
21

Presumably, when you iterate through your cells, the idea would be to apply the format at that.

for row in ws.iter_rows():
    for cell in row:
        cell.style.alignment.wrap_text=True

There is also a fair amount more detail into how to use the wrap text style here Writing multi-line strings into cells using openpyxl

Hope this helps.

Community
  • 1
  • 1
Allan B
  • 329
  • 2
  • 9
  • 9
    When using indices to call cells, this should work: `from openpyxl.styles import Alignment` `_sheet.cell(1, 2).alignment = Alignment(wrapText=True)` – Petr Szturc May 17 '18 at 13:14
10
import os
import openpyxl
from openpyxl.styles import Alignment, Font
from openpyxl.cell import Cell
#format cells with word wrap and top alignment    
for row in ws2.iter_rows():  
    for cell in row:      
        cell.alignment = Alignment(wrap_text=True,vertical='top') 
user13577089
  • 101
  • 1
  • 3
5

Update alignment in openpyxl v3

Many of the answers set wrapText=True but clobber existing alignment options. This is no good.

Using openpyxl v3.0.4, I did the following:

import copy

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

The original poster's solution uses:

cell.alignment =  cell.alignment.copy(wrapText=True)

But this produced the following warning:

DeprecationWarning: Call to deprecated function copy (Use copy(obj) or cell.obj = cell.obj + other).
  cell.alignment =  cell.alignment.copy(wrapText=True)
Daniel Himmelstein
  • 1,759
  • 1
  • 21
  • 26
-1

Iterates all cells

  for rows in ws.iter_rows(min_row=1, min_col=1):
    for cell in rows:
      print('cell %s %s' % (cell.coordinate,cell.value))

* Tested with Python:3.4.2 - openpyxl:2.4.1 *

stovfl
  • 14,998
  • 7
  • 24
  • 51