Search code examples
xlsxwriter

Assign default excel format to cell


I'm using XlsxWriter to format cells containing currency formatted strings as follows:

currency_cell_format = self.workbook.add_format()
currency_cell_format.set_num_format('_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)')
self.worksheet.write_string(row=r, col=c, string=value, cell_format=currency_cell_format)

The expected outcome is that the format type when viewing the worksheet in excel should be a Number (specifically $). There appears to be no visual formatting (however the type is Custom) and the values are left justified (instead of the typical right justified when the cell is Numeric formatted.

How can I assign the default Excel format types to cells using Xslxwriter so that the columns are Numeric formatted (instead of Custom) thus enabling functionality like calculations?

Note: Applying bold or font formatting works correctly. I tried the hex index values but the cells remained unformatted.


Solution

  • In Excel assigning a number format to a string has no effect. The same applies when using XlsxWriter, particularly if you are using write_string().

    You should convert your data to a number, if it is numeric, and then apply the format using write_number() or write().