Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnicodeDecodeError error writing .xlsx file using xlsxwriter

I am trying to write about 1000 rows to a .xlsx file from my python application. The data is basically a combination of integers and strings. I am getting intermittent error while running wbook.close() command. The error is the following:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 15: 
                     ordinal not in range(128)

My data does not have anything in unicode. I am wondering why the decoder is being at all. Has anyone noticed this problem?

like image 783
Santanu C Avatar asked Jan 15 '14 23:01

Santanu C


2 Answers

0xc3 is "À". So what you need to do is change the encoding. Use the decode() method.

string.decode('utf-8')

Also depending on your needs and uses you could add

# -*- coding: utf-8 -*-

at the beginning of your script, but only if you are sure that the encoding will not interfere and break something else.

like image 151
Alexander Ejbekov Avatar answered Oct 15 '22 14:10

Alexander Ejbekov


As Alex Hristov points out you have some non-ascii data in your code that needs to be encoded as UTF-8 for Excel.

See the following examples from the docs which each have instructions on handling UTF-8 with XlsxWriter in different scenarios:

  • Example: Simple Unicode with Python 2
  • Example: Simple Unicode with Python 3
  • Example: Unicode - Polish in UTF-8
like image 4
jmcnamara Avatar answered Oct 15 '22 14:10

jmcnamara