1#######################################################################
2#
3# An example of using Python and XlsxWriter to write some "rich strings",
4# i.e., strings with multiple formats.
5#
6# Copyright 2013-2021, John McNamara, jmcnamara@cpan.org
7#
8import xlsxwriter
9
10workbook = xlsxwriter.Workbook('rich_strings.xlsx')
11worksheet = workbook.add_worksheet()
12
13worksheet.set_column('A:A', 30)
14
15# Set up some formats to use.
16bold = workbook.add_format({'bold': True})
17italic = workbook.add_format({'italic': True})
18red = workbook.add_format({'color': 'red'})
19blue = workbook.add_format({'color': 'blue'})
20center = workbook.add_format({'align': 'center'})
21superscript = workbook.add_format({'font_script': 1})
22
23# Write some strings with multiple formats.
24worksheet.write_rich_string('A1',
25                            'This is ',
26                            bold, 'bold',
27                            ' and this is ',
28                            italic, 'italic')
29
30worksheet.write_rich_string('A3',
31                            'This is ',
32                            red, 'red',
33                            ' and this is ',
34                            blue, 'blue')
35
36worksheet.write_rich_string('A5',
37                            'Some ',
38                            bold, 'bold text',
39                            ' centered',
40                            center)
41
42worksheet.write_rich_string('A7',
43                            italic,
44                            'j = k',
45                            superscript, '(n-1)',
46                            center)
47
48# If you have formats and segments in a list you can add them like this:
49segments = ['This is ', bold, 'bold', ' and this is ', blue, 'blue']
50worksheet.write_rich_string('A9', *segments)
51
52workbook.close()
53