On Tue, May 20, 2014 at 10:13 AM, Paul Pharr <
paul...@gmail.com> wrote:
> And even if a text cell is prefixed by an apostrophe, excel
> still flags the cell as having an error because it contains only
> numeric information (!!)
For good or ill, that's just how Excel is.
> I have tried to format the cell as text using format like
> xlwt.easyxf(num_format_str="@"), but that leaves the error
> condition in place.
This is true, but it is resistant to simple user edits. (They would
have to choose a new cell format.)
> This leaves the old trick of setting a text field using a formula
> [which] displays the label with no error condition, and if
> the user edits it, it is not accidentally interpreted numerically.
It doesn't show the error, but it does show the formula if the cell is
selected. This may either be confusing to the user, or may tempt the
user to "correct" the cell by removing the weird characters.
> [Cells containing formulas may initially appear blank when read
> by software other than Excel.] I assume this is because Excel
> writes cached results for formulas to the file, but my method of
> writing with xlwt does not.
xlwt indeed does not write any calculation results. You will find
that almost all software which writes Excel files, other than Excel
itself, behaves similarly. This is because (1) it's highly nontrivial
to fully parse Excel formulas, (2) even if correctly parsed, it's
difficult to *exactly* duplicate the calculations that Excel itself
would perform; thus the results cannot be guaranteed to be "correct"
from an Excel point of view, and (3) because of the previous reasons,
Microsoft itself recommends that third-party software not attempt to
evaluate formulas.
That said, if you want to calculate formula results yourself and write
both the value and the formula, it is possible to do so. To my
knowledge, xlwt doesn't expose this functionality, but XlsxWriter
does. The thing about XlsxWriter is that it only generates the newer
Excel 2007+ (.xlsx) format. If that's a showstopper, then you have to
either patch xlwt yourself or live with one of the suboptimal choices
you've already found. Of the xlwt options, I personally prefer
setting the number format string to '@'.
One final caveat: I believe XlsxWriter currently has a bit of a bug
when it comes to writing formula values that look numeric but aren't
(your very situation). I will open a ticket for this if I can't find
that the issue is already open or fixed. The developer (John
McNamara) is usually quite responsive, but if time is critical, I can
point you to where you need to put the temporary duct tape in the
code.
John Y.