Can text be wrapped in a cell?

1,471 views
Skip to first unread message

shawn....@gmail.com

unread,
Dec 12, 2013, 4:38:41 PM12/12/13
to openpyx...@googlegroups.com
Is there a way to wrap text in a cell, more specifically, in merged cells?  I've figured out the merge, but don't see any way to specifiy that the value should be wrapped.  Thanks in advance

Adam Morris

unread,
Dec 12, 2013, 8:42:50 PM12/12/13
to openpyx...@googlegroups.com, shawn....@gmail.com
In general, most styling is supported, but it's there isn't extensive documentation, often the best place to start is in openpyxl/style.py.

To wrap text or shrink to fit:

    from openpyxl.workbook import Workbook

    wb = Workbook()
    ws = wb.worksheets[0]

    ws.cell('A1').value = 'This is long text'
    ws.cell('A1').style.alignment.wrap_text = True

    ws.cell('A2').value = 'This is also long text'
    ws.cell('A2').style.alignment.shrink_to_fit = True

    ws.merge_cells('A1:B1')  # A1 still has wrap text


In general, wrap text works with merge cells - however, you may need to set your row height manually... as when I tested this, the row height didn't expand automatically.

Digging into it further, excel behaves a bit funny with the merge cells and wrap text - it looks like it assigns a row height based on what happens first... if you merge a cell and then wrap-text, it doesn't change the row height, even if you set the format of the cell to auto-row height, but if you wrap-text and then merge, it adjusts the row automatically to begin with, and keeps it adjusted after the row height changes.

Cheers

shawn....@gmail.com

unread,
Dec 13, 2013, 11:40:47 AM12/13/13
to openpyx...@googlegroups.com, shawn....@gmail.com
Perfect!  Thanks so much.
Reply all
Reply to author
Forward
0 new messages