Python 使用 openpyxl 将多行字符串写入单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15370432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:55:54  来源:igfitidea点击:

Writing multi-line strings into cells using openpyxl

pythonopenpyxl

提问by user1514631

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?

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

采纳答案by jmcnamara

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

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

In openpyxlyou can set the wrap_textalignment property to wrap multi-line strings:

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

enter image description here

在此处输入图片说明

This is also possible with the XlsxWritermodule.

这也可以通过XlsxWriter模块实现。

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

回答by Charlie Clark

The API for styles changed for openpyxl >= 2. The following code demonstrates the modern API.

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