我正在尝试将数据写入具有多个换行符的单元格(我相信\ n),生成的.xlsx删除了换行符。 有没有办法保持这些换行符?
答案 0 :(得分:30)
针对openpyxl> = 2更改了样式的API。以下代码演示了现代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")
答案 1 :(得分:26)
在openpyxl
中,您可以设置wrap_text
alignment属性以包装多行字符串:
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')
XlsxWriter模块也可以这样做。
这是一个小工作示例:
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()
答案 2 :(得分:0)
还有一个附加选项,您可以在文本“”“中使用文本阻止”“”,在此处将“”“与文本自动换行布尔值对齐使用,并获得所需的结果。
from openpyxl import Workbook
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')