使用openpyxl将多行字符串写入单元格 [英] Writing multi-line strings into cells using openpyxl

查看:883
本文介绍了使用openpyxl将多行字符串写入单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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

openpyxl中,您可以设置wrap_text对齐方式属性以包装多行字符串:

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

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

This is also possible with the XlsxWriter module.

这是一个小例子:

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

这篇关于使用openpyxl将多行字符串写入单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆