Writing multi-line strings into cells using openpyxl

后端 未结 3 761
迷失自我
迷失自我 2020-12-09 08:09

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?

3条回答
  •  北海茫月
    2020-12-09 09:11

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

提交回复
热议问题