user2782845 user2782845 - 1 year ago 394
Python Question

Writing multi-line strings to cells using xlwt module

Is there a way to write multi-line strings into an excel cell with just the xlwt module? (I saw answers suggesting use of openpyxl module)


method ignores the \n escape sequence. So, just xlwt, is it possible? Thanks in advance.

Answer Source

I found the answer in the python-excel Google Group. Using sheet.write() with the optional style argument, enabling word wrap for the cell, does the trick. Here is a minimum working example:

import xlwt
book = xlwt.Workbook()
sheet = book.add_sheet('Test')

# A1: no style, no wrap, despite newline
sheet.write(0, 0, 'Hello\nWorld')

# B1: with style, there is wrap
style = xlwt.XFStyle()
style.alignment.wrap = 1
sheet.write(0, 1, 'Hello\nWorld', style)'test.xls')

While in cell A1 shows HelloWorld without linebreak, cell B1 shows Hello\nWorld (i.e. with linebreak).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download