XlsxWriter set global font size
Asked Answered
F

1

13

How do permanently set the font size using xlswriter when you first create the workbook?

I tried:

book = xlsxwriter.Workbook(os.getcwd() + '\\test.xlsx')
sheet1 = book.add_worksheet()
format = book.add_format()
format.set_font_size(10)

But I still get the default size 11 in the output. What is the issue?

Froze answered 16/5, 2017 at 2:17 Comment(0)
S
20

1, For single cell font size, you have to pass the format to the write like this:

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

# Add a bold format to use to highlight cells.
bold = workbook.add_format({'bold': True})
# Add a font size 10 format.
format = workbook.add_format()
format.set_font_size(10)
# Write some simple text.
worksheet.write('A1', 'Hello', format)

# Text with formatting.
worksheet.write('A2', 'World', bold)

# Write some numbers, with row/column notation.
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)


workbook.close()

Hello will be set to font size 10.

enter image description here

Update: 2, For all cells font size, you could set the default format of the workbook:

import xlsxwriter
workbook = xlsxwriter.Workbook('demo.xlsx')

# default cell format to size 10 
workbook.formats[0].set_font_size(10)

worksheet = workbook.add_worksheet()


# Write some simple text.
worksheet.write('A1', 'Hello')

worksheet.write('A2', 'World')

# Write some numbers, with row/column notation.
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)

workbook.close()

All cell will change to font size 10:

enter image description here

Shrovetide answered 16/5, 2017 at 2:58 Comment(7)
is there any way to set this globally? I write many times to this worksheet / book and I want to avoid passing it every time since I want it all size 10Froze
The workaround is okay but note that it breaks the sizing of images, graphs and other objects inserted into the worksheet. This is the main reason that this feature isn't currently supported in XlsxWriter.Evoy
@Evoy Thanks for your comments about this point, it is very important for us to know about it.Shrovetide
Thanks, but this still actually doesn't work. Is it possible when writing with different font colors, this sizing gets reset?Froze
yes, it will overwrite the font size to be 11, if you add other format like set_font_color and set_bold.Shrovetide
Is it possible then to set it at the end using your method? Like when I am done writing everything, just change the font size to 10.Froze
For more info - groups.google.com/g/python-excel/c/0vWPLht7K64Joslin

© 2022 - 2024 — McMap. All rights reserved.