Xlsx Writer:在单个单元格中写入多种格式的字符串

Xlsx Writer: Writing strings with multiple format in a single cell

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

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

我想使用如下所示的 Xlsx Writer 在 excel 单元格中写入此字符串。

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

这就是我所做的。

description_combined = 
    '''
    firstline: abc
    secondline: bcd
    thirdline: efg
    '''
    spanInserted = []
    spanInserted = description_combined.split("\n")
    result = ''

    for spans in spanInserted:
        strr1 =  '{}:'.format(spans.split(":")[0])
        strr2 = spans.split(":")[1]
        result += '''bold , "{}" , "{}" ,'''.format(str(strr1),str(strr2))

    result = result[:-1]
    # print result

    worksheet.write_rich_string('A1', result)  


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

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

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

希望对您有所帮助

write_string() 方法将列表作为参数,但您传递的是字符串。

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

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

worksheet.write_rich_string('A1', *result)

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

import xlsxwriter

workbook = xlsxwriter.Workbook('rich_strings.xlsx')
worksheet = workbook.add_worksheet()

worksheet.set_column('A:A', 20)
worksheet.set_row(0, 60)

bold = workbook.add_format({'bold': True})
text_wrap = workbook.add_format({'text_wrap': True, 'valign': 'top'})

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

result.append(text_wrap)

worksheet.write_rich_string('A1', *result)

workbook.close()

输出: