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)
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.
The openpyxl is a Python library to read and write Excel 2010 xlsx/xlsm/xltx/xltm files.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With