11

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?

jmcnamara
  • 38,196
  • 6
  • 90
  • 108
guy
  • 1,021
  • 2
  • 16
  • 40

1 Answers1

18

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

Tiny.D
  • 6,466
  • 2
  • 15
  • 20
  • 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 10 – guy May 16 '17 at 03:01
  • 5
    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. – jmcnamara May 16 '17 at 08:47
  • @jmcnamara Thanks for your comments about this point, it is very important for us to know about it. – Tiny.D May 16 '17 at 08:50
  • Thanks, but this still actually doesn't work. Is it possible when writing with different font colors, this sizing gets reset? – guy May 16 '17 at 11:47
  • yes, it will overwrite the font size to be 11, if you add other format like `set_font_color` and `set_bold`. – Tiny.D May 16 '17 at 12:27
  • 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. – guy May 16 '17 at 16:35
  • For more info - https://groups.google.com/g/python-excel/c/0vWPLht7K64 – Lijo Abraham Feb 25 '21 at 10:35