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

时间:2016-09-08 06:44:54

标签: python excel python-2.7 xlsx xlsxwriter

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

'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单元格中得到的结果:

  

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

2 个答案:

答案 0 :(得分:4)

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

输出:

enter image description here

答案 1 :(得分: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()

我希望这会有所帮助