Writing multi-line strings into cells using openpyxl

Question:

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?

Asked By: user1514631

||

Answers:

Disclaimer: This won’t work in recent versions of Openpyxl. See other answers.

In openpyxl you can set the wrap_text alignment property to wrap multi-line strings:

from openpyxl import Workbook

workbook = Workbook()
worksheet = workbook.worksheets[0]
worksheet.title = "Sheet1"

worksheet.cell('A1').style.alignment.wrap_text = True
worksheet.cell('A1').value = "Line 1nLine 2nLine 3"

workbook.save('wrap_text1.xlsx')

enter image description here

This is also possible with the XlsxWriter module.

Here is a small working example:

from xlsxwriter.workbook import Workbook

# Create an new Excel file and add a worksheet.
workbook = Workbook('wrap_text2.xlsx')
worksheet = workbook.add_worksheet()

# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 20)

# Add a cell format with text wrap on.
cell_format = workbook.add_format({'text_wrap': True})

# Write a wrapped string to a cell.
worksheet.write('A1', "Line 1nLine 2nLine 3", cell_format)

workbook.close()
Answered By: jmcnamara

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 1nLine 2nLine 3"
ws['A1'].alignment = Alignment(wrapText=True)
wb.save("wrap.xlsx")
Answered By: Charlie Clark

Just an additional option, you can use text blocking """ my cell info here """ along with the text wrap Boolean in alignment and get the desired result as well.

from openpyxl import Workbook
from openpyxl.styles import Alignment

wb= Workbook()
sheet= wb.active
sheet.title = "Sheet1"

sheet['A1'] = """Line 1
Line 2
Line 3"""

sheet['A1'].alignment = Alignment(wrapText=True)

wb.save('wrap_text1.xlsx')
Answered By: Steven Barnard

Just in case anyone is looking for an example where we iterate over all cells to apply wrapping:

Small working example:

import pandas as pd
from openpyxl import Workbook
from openpyxl.styles import Alignment
from openpyxl.utils.dataframe import dataframe_to_rows

# create a toy dataframe. Our goal is to replace commas (',') with line breaks and have Excel rendering n as line breaks.
df = pd.DataFrame(data=[["Mark", "Student,26 y.o"],
                        ["Simon", "Student,31 y.o"]], 
                  columns=['Name', 'Description'])

# replace comma "," with 'n' in all cells
df = df.applymap(lambda v: v.replace(',', 'n') if isinstance(v, str) else v)

# Create an empty openpyxl Workbook. We will populate it by iteratively adding the dataframe's rows.
wb = Workbook()
ws = wb.active # to get the actual Worksheet object

# dataframe_to_rows allows to iterate over a dataframe with an interface
# compatible with openpyxl. Each df row will be added to the worksheet.
for r in dataframe_to_rows(df3, index=True, header=True):
    ws.append(r)

# iterate over each row and row's cells and apply text wrapping.
for row in ws:
  for cell in row:
    cell.alignment = Alignment(wrapText=True)

# export the workbook as an excel file.
wb.save("wrap.xlsx")
Answered By: Francesco Pisu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.