Xlsx Writer:在sing中编写多种格式的字符串

2024-09-30 00:35:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含多个分号的字符串。在

'firstline: abc \n secondline: bcd \n thirdline: efg'

我想用下面的Xlsx Writer在excel单元格中写这个字符串。在

第一行:abc
第二行:bcd
第三行:efg

我就是这么做的。在

^{pr2}$


这是我在excel单元格中得到的结果:

bold , "firstline:" , "abc" ,bold , "secondline:" , "bcd" ,bold , "thirdline:" , "efg"


Tags: 字符串xlsxexcelwriterabcboldpr2bcd
2条回答

jmcnamara的解决方案很有效。我发布了一个类似的可能的解决方案,但动态的。在

import xlsxwriter
workbook = xlsxwriter.Workbook("<your path>")
worksheet = workbook.add_worksheet()
# add style for first column
cell_format = workbook.add_format({'bold': True})
text_wrap = workbook.add_format({'text_wrap': True, 'valign': 'top'})
data = []
description_combined = 'firstline: abc \n secondline: bcd \n thirdline: efg'
# prepare list of list
for item in description_combined.split("\n"):
    data.append(cell_format)
    data.append(item.split(":")[0].strip() + ":")
    data.append(item.split(":")[1] + "\n")

# write data in one single cell
data.append(text_wrap)

worksheet.write_rich_string('A1', *data)

workbook.close()

我希望这会有帮助

^{}方法接受列表作为参数,但传递的是字符串。在

您应该使用类似的方法传递字符串和格式列表:

result = [bold, 'firstline: ',  'abc',
          bold, 'secondline: ', 'bcd',
          bold, 'thirdline: ',  'efg']

worksheet.write_rich_string('A1', *result)

但是,如果您还希望文本换行,则需要在列表末尾添加text_wrap单元格格式,并在希望换行的位置添加换行符。像这样:

^{pr2}$

输出:

enter image description here

相关问题 更多 >

    热门问题