Xlsx Writer:在单个单元格中编写多种格式的string

我有一个多个分号的string。

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

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

第一线 :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中获得的结果:

粗体,“firstline:”,“abc”,粗体,“secondline:”,“bcd”,粗体,“thirdline:”,“efg”

jmcnamara的解决scheme运作良好。 我发布了类似的可能的解决scheme,但dynamic的。

 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()方法将列表作为参数,但传递的是string。

你应该使用这样的东西来传递你的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() 

输出:

在这里输入图像说明