Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 255
user1906450 Avatar asked Apr 19 '15 08:04

user1906450


People also ask

How do I change the default format general to format text in Excel?

Select the cells with the Excel Style. Right-click the applied style in Home > Cell Styles. Select Modify > Format to change what you want.


1 Answers

  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

Update: See also this newer, more specific, section of the XlsxWriter docs on Number Format Categories.

like image 63
jmcnamara Avatar answered Sep 23 '22 01:09

jmcnamara