I’m writing excel sheets with xlwt, and it’s working great except for one little thing. I would like to display the number zero as a dash (-), the way that it does with accounting. However, I don’t want it to show the dollar sign, $, before everything, and I don’t want it to have commas at the thousands.
I thought this would be a fairly easy problem to solve, I just go and set the format in excel to what I want, then view “Format -> Custom Format” to get the exact format string. Doing so gives me _(* (#,##0);_(* "-"_);_(@_) to use (this doesn’t deal with the commas, but does display zeros as dashes and removes the $).
Unfortunately, when I use that string in xlwt, it seems to reset it to the accounting default: _($* #,##0_);_($* (#,##0);_($* "-"_);_(@_). I think this is a bug in xlwt, but does anyone know if there’s a way around this to let me do what I want to do?
Edit:
Don’t know why it works, but my problem seems to be solved by removing the commas from the string. That is changing:
‘_(* #,##0_);_(* (#,##0);_(* “-“);(@)’
to
‘(* ###0_);_(* (###0);_(* “-“);(@_)’
I believe this works because xlwt doesn’t see it as a custom format when you just remove the $ and instead writes as the accounting default, but when you remove the $ and the commas it kicks it into the custom format method, which is what I want.
In response to John, I’m using these with the tablestyle.numformat attribute. basic code would be:
style = xlwt.xlwt.XFStyle()
style.num_format_str = '_(* ###0_);_(* (###0);_(* "-"_);_(@_)'
The only thing I would ideally like to change now is make negative numbers appear like -5, rather than accounting (5), but I think I can live with how it is now. It might be nice if someone could explain how the excel format strings work though, I can see a bit of rhyme/reason in them but am mostly confused by these long string of numbers that I just cut and paste in.
Here is some minimal working code. In the output spreadsheet, column A is using your original format, B is using what you first appeared to be wanting (accounting format), and column C gives you non-accounting format.
You may like to read the tutorial that you can access via this link.
No good telling you to RTFM because there hasn’t been a manual since about Excel 5.0 AFAIK but you can always HTF1K (hit the F1 key) then type
custom formatsinto the search box and then FYN (follow your nose).