Writing multi-line strings into cells using openpyxl

user1514631 picture user1514631 · Mar 12, 2013 · Viewed 34.9k times · Source

I'm trying to write data into a cell, which has multiple line breaks (I believe \n), the resulting .xlsx has line breaks removed. Is there a way to keep these line breaks?

Answer

Charlie Clark picture Charlie Clark · Jun 6, 2016

The API for styles changed for openpyxl >= 2. The following code demonstrates the modern API.

from openpyxl import Workbook
from openpyxl.styles import Alignment

wb = Workbook()
ws = wb.active # wb.active returns a Worksheet object
ws['A1'] = "Line 1\nLine 2\nLine 3"
ws['A1'].alignment = Alignment(wrapText=True)
wb.save("wrap.xlsx")