Xlsx Writer: Writing stings with multiple format in a single cell
<p>I have a string with multiple semicolons.</p>

<pre><code>'firstline: abc \n secondline: bcd \n thirdline: efg'
</code></pre>

<p>I want to write this strings in excel cell using Xlsx Writer like below.</p>

<p><b>firstline</b>: abc <br>
<b>secondline</b>: bcd <br>
<b>thirdline</b>: efg <br></p>

<p>This is what I did.</p>

<pre><code>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)  
</code></pre>

<p><br>
This is the result I got in excel cell:</p>

<blockquote>
  <p>bold , "firstline:" , "abc" ,bold , "secondline:" , "bcd" ,bold , "thirdline:" , "efg"</p>
</blockquote>

<p>The <a href="http://xlsxwriter.readthedocs.io/worksheet.html#worksheet-write-rich-string" rel="nofollow"><code>write_string()</code></a> method takes a list as an argument but you are passing a string.</p>

<p>You should use something like this to pass your list of strings and formats:</p>

<pre><code>result = [bold, 'firstline: ',  'abc',
          bold, 'secondline: ', 'bcd',
          bold, 'thirdline: ',  'efg']

worksheet.write_rich_string('A1', *result)
</code></pre>

<p>However, if you also want the text to be wrapped you will need to add a <code>text_wrap</code> cell format at the end of the list and add newlines for where you want the wrap to occur. Something like this:</p>

<pre><code>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()
</code></pre>

<p>Output:</p>

<p><a href="http://i.stack.imgur.com/tEBXb.png" rel="nofollow"><img src="http://i.stack.imgur.com/tEBXb.png" alt="enter image description here"></a></p>

python excel python-2.7 xlsx xlsxwriter