Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing multi-line strings to cells using xlwt module

Tags:

Python: 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)

The sheet.write() method ignores the \n escape sequence. So, just xlwt, is it possible? Thanks in advance.

like image 689
user2782845 Avatar asked Sep 16 '13 07:09

user2782845


People also ask

How do I merge cells in Excel with XLWT?

There are two methods on the Worksheet class to do this, write_merge and merge . merge takes existing cells and merges them, while write_merge writes a label (just like write ) and then does the same stuff merge does. Both take the cells to merge as r1, r2, c1, c2 , and accept an optional style parameter.

What is import XLWT?

This is a library for developers to use to generate spreadsheet files compatible with Microsoft Excel versions 95 to 2003. The package itself is pure Python with no dependencies on modules or packages outside the standard Python distribution.


1 Answers

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)
book.save('test.xls')

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

like image 200
ojdo Avatar answered Sep 19 '22 15:09

ojdo