Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing multi-line strings into cells using openpyxl

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?

like image 498
user1514631 Avatar asked Mar 12 '13 19:03

user1514631


People also ask

How do I write to a cell in openpyxl?

Openpyxl write to a cell There are two basic ways to write to a cell: using a key of a worksheet such as A1 or D3, or using a row and column notation with the cell method. In the example, we write two values to two cells. Here, we assing a numerical value to the A1 cell.


2 Answers

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") 
like image 132
Charlie Clark Avatar answered Sep 22 '22 14:09

Charlie Clark


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 1\nLine 2\nLine 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 1\nLine 2\nLine 3", cell_format)  workbook.close() 
like image 24
jmcnamara Avatar answered Sep 21 '22 14:09

jmcnamara