SoFunction
Updated on 2024-11-14

Python solves the problem of throwing exceptions when writing Chinese to Excel.

Recently received the demand of the business sector, need to send the statistical results daily to the business sector, in the debugging python script, the exported Excel header for the Chinese, always throws the following exception

Traceback (most recent call last): 
 File "", line 99, in <module> 
 export() 
 File "", line 54, in export 
 (out_path) 
 File "/usr/lib/python2.7/site-packages/xlwt-1.2.0-py2./xlwt/", line 710, in save 
 (filename_or_stream, self.get_biff_data()) 
 File "/usr/lib/python2.7/site-packages/xlwt-1.2.0-py2./xlwt/", line 674, in get_biff_data 
 shared_str_table = self.__sst_rec() 
 File "/usr/lib/python2.7/site-packages/xlwt-1.2.0-py2./xlwt/", line 636, in __sst_rec 
 return self.__sst.get_biff_record() 
 File "/usr/lib/python2.7/site-packages/xlwt-1.2.0-py2./xlwt/", line 77, in get_biff_record 
 self._add_to_sst(s) 
 File "/usr/lib/python2.7/site-packages/xlwt-1.2.0-py2./xlwt/", line 92, in _add_to_sst 
 u_str = upack2(s, ) 
 File "/usr/lib/python2.7/site-packages/xlwt-1.2.0-py2./xlwt/", line 50, in upack2 
 us = unicode(s, encoding) 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128) 

The solution is to set the character set when creating the workbook:

workbook = (encoding = 'utf-8')

The normal default encoding is ascii, so writing Chinese decoding will throw an exception, just set it to utf-8.

Above this Python to solve the problem of writing Chinese to Excel throws an exception is all I have shared with you, I hope to be able to give you a reference, and I hope you support me more.