28

我正在尝试将数据写入具有多个换行符的单元格(我相信 \n),生成的 .xlsx 已删除换行符。有没有办法保留这些换行符?

4

4 回答 4

59

针对 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")
于 2016-06-06T07:27:00.323 回答
38

免责声明:这在 Openpyxl 的最新版本中不起作用。查看其他答案。

openpyxl您可以设置wrap_text对齐属性来包装多行字符串:

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()
于 2013-03-13T11:35:41.283 回答
1

只是一个附加选项,您可以在此处使用文本阻止“”“我的单元格信息”“””以及对齐的文本换行布尔值,并获得所需的结果。

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')
于 2020-09-28T12:14:48.057 回答
0

以防万一有人正在寻找我们遍历所有单元格以应用包装的示例:

小工作示例:

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")
于 2021-10-25T13:17:42.247 回答