尝试使用Python xlwt保存Excel文件时的UnicodeDecodeError

我正在运行一个Python脚本,将使用BeautifulSoup发现的HTML代码写入Excel电子表格列的多行。

[...] Col_HTML = 19 w_sheet.write(row_index, Col_HTML, str(HTML_Code)) wb.save(output) 

当试图保存文件时,我得到以下错误信息:

 Traceback (most recent call last): File "C:\Users\[..]\src\MYCODE.py", line 201, in <module> wb.save(output) File "C:\Python27\lib\site-packages\xlwt-0.7.5-py2.7.egg\xlwt\Workbook.py", line 662, in save doc.save(filename, self.get_biff_data()) File "C:\Python27\lib\site-packages\xlwt-0.7.5-py2.7.egg\xlwt\Workbook.py", line 637, in get_biff_data shared_str_table = self.__sst_rec() File "C:\Python27\lib\site-packages\xlwt-0.7.5-py2.7.egg\xlwt\Workbook.py", line 599, in __sst_rec return self.__sst.get_biff_record() File "C:\Python27\lib\site-packages\xlwt-0.7.5-py2.7.egg\xlwt\BIFFRecords.py", line 76, in get_biff_record self._add_to_sst(s) File "C:\Python27\lib\site-packages\xlwt-0.7.5-py2.7.egg\xlwt\BIFFRecords.py", line 91, in _add_to_sst u_str = upack2(s, self.encoding) File "C:\Python27\lib\site-packages\xlwt-0.7.5-py2.7.egg\xlwt\UnicodeUtils.py", line 50, in upack2 us = unicode(s, encoding) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 5181: ordinal not in range(128) 

我已经成功编写了过去的Python脚本来写入工作表。 这是我第一次尝试写一个string的HTML到单元格,我想知道是什么原因造成的错误,以及如何我可以修复它。

在将HTML_Code传递给w_sheet.write之前使用这一行

 HTML_Code = HTML_Code.decode('utf-8') 

因为在错误行UnicodeDecodeError: 'ascii' codec can't decode ,Python正在尝试将unicode解码为ascii,因此您需要使用正确的编码格式(即utf-8解码unicode。

所以你有了:

 Col_HTML = 19 HTML_Code = HTML_Code.decode('utf-8') w_sheet.write(row_index, Col_HTML, str(HTML_Code))