23

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.

user2782845
  • 235
  • 1
  • 2
  • 5

3 Answers3

36

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).

ojdo
  • 8,280
  • 5
  • 37
  • 60
3

If you don't use XFStyle and instead easyxf it's done like this:

import xlwt

style_head = xlwt.easyxf('alignment: wrap True')

row = 1
cell = 1
book = xlwt.Workbook(encoding='utf-8')
sheet = book.add_sheet()
sheet.write(row, cell, 'cell value', style_head)
Sam_slo
  • 141
  • 1
  • 1
  • 10
  • Oh, that's a cool API addition. The examples folder in xlwt's repo even shows how to create a full, nicely formatted report table (headings, custom number format strings): [xlwt_easyxf_simple_demo.py](https://github.com/python-excel/xlwt/blob/master/examples/xlwt_easyxf_simple_demo.py). – ojdo Sep 19 '19 at 10:50
0

There are a few things you could try:

  1. Windows handles new lines differently to Unix/Linux. While \n (line feed) character is the standard Unix method and also used in Python, Windows requires a carriage return and line feed. You could therefore try replacing \n with \r\n.
  2. If this does not work then try replacing them with the ascii characters {chr(13) and chr(10)} inside a formula.
  3. If this still doesn't work then it may be worth trying this article which suggests a rather more long winded way of approaching the problem.
ChrisProsser
  • 12,598
  • 6
  • 35
  • 44