1

I'm trying to save some text with xlwt module, creating new xls document and saving text there.So far it worked great, until I came across unicode text: for example simple string '80°'.

When I call book.save('simple.xls') I get UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2.Is there any way I can avoid that?

John Y
  • 14,123
  • 2
  • 48
  • 72
Zed
  • 5,683
  • 11
  • 49
  • 81

1 Answers1

3

Instead of writing a regular string, write a Unicode string. For example, instead of

ws.write(r, c, '80°')

do

ws.write(r, c, '80°'.decode('cp1252'))

(Of course, pick the appropriate encoding for your data.)

John Y
  • 14,123
  • 2
  • 48
  • 72
  • I have a similar problem right now. I'm passing a unicode object to ws.write() in my case. Your code above, by using decode(), will also pass a unicode object. I have a feeling this isn't going to work. Right now I actually think you need to call encode() to change it into a good old string that ws.write() can handle. What remains to be seen is what it has to be encoded as, and if both OpenOffice and Excel is going to be happy with that. – izak Jul 25 '14 at 08:55
  • See http://stackoverflow.com/questions/7184454/has-anyone-been-able-to-write-out-utf-8-characters-using-pythons-xlwt – izak Jul 25 '14 at 08:57
  • 1
    @izak: Instead of just "having a feeling", why don't you try it and be sure? The code in my answer works on my machine, and it follows the guidance given by the closest thing there is to an official manual: [this PDF by Chris Withers](http://www.simplistix.co.uk/presentations/python-excel.pdf). (See the section titled "Unicode", which as of this writing is toward the bottom of page 22.) – John Y Jul 25 '14 at 14:42
  • @izak: As if the reference I gave before is not authoritative enough, the top-voted and accepted answer to the question you linked to was written by the author of xlwt himself, and he explicitly states xlwt accepts (and effectively prefers) `unicode` input. – John Y Jul 25 '14 at 15:02
  • Fair enough :-) I did manage to solve my own problem as well, though by now I cannot even remember what I did, suffice it to say unicode isn't as big a problem as I thought. – izak Oct 13 '14 at 13:06