Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply 'wrap_text' to all cells using openpyxl

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)
like image 822
DerRabe Avatar asked Feb 14 '17 00:02

DerRabe


People also ask

How do I style a cell in openpyxl?

To change a style property of a cell, first you either have to copy the existing style object from the cell and change the value of the property or you have to create a new style object with the desired settings. Then, assign the new style object to the cell. Save this answer. Show activity on this post.

Can openpyxl write XLS?

The openpyxl is a Python library to read and write Excel 2010 xlsx/xlsm/xltx/xltm files.


2 Answers

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)
like image 75
SuperNova Avatar answered Sep 20 '22 04:09

SuperNova


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.

like image 42
Allan B Avatar answered Sep 21 '22 04:09

Allan B