How to apply format as 'Text' and 'Accounting' using xlsxwriter

user1906450 picture user1906450 · Apr 19, 2015 · Viewed 7.1k times · Source

I have been using xlsxwriter for a while and find it to be really helpful. I have used it for multiple purposes like custom data validation, custom formats etc However there are two things i am not able to perform.

  1. set format of a cell to 'text' and not 'general'. i have tried the apis write_string, write_blank but they always apply the format general

  2. set format as accounting. i have tried add_format({'num_format': '#,###'}. but this simply sets the format as 'custom' instead of accounting

Please help.

Answer

jmcnamara picture jmcnamara · Apr 19, 2015
  1. To set a cell format to text you need to apply a text format to the cell (just like in Excel). To do this you set the num_format property of the format to '@'.
  2. If you set a string format like #,### then this will generally show up in Excel as a custom format even if it equates to one of the built-in formatting categories like accountancy. This is the same behaviour as Excel.

In order to get one of the built-in formats you need to use a format index instead of a string. The table in the num_format section of the docs shows the available indices and their equivalent string formats. For accountancy you need to use one of the accountancy-like format indices such as 44 (_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)). The example below shows both of these:

import xlsxwriter

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

worksheet.set_column('A:A', 20)

format1 = workbook.add_format({'num_format': '@'})
format2 = workbook.add_format({'num_format': 44})

worksheet.write(0, 0, 1234)
worksheet.write(1, 0, 1234, format1)
worksheet.write(2, 0, 1234, format2)

workbook.close()

Output:

enter image description here