我正在运行一个 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脚本来写入工作表。这是我第一次尝试将 HTML 字符串写入单元格,我想知道是什么导致了错误以及如何修复它。
最佳答案
在将 HTML_Code
传递给 w_sheet.write
之前使用此行
HTML_Code = HTML_Code.decode('utf-8')
因为,在错误行 UnicodeDecodeError: 'ascii' codec can't Decode
中,Python 正在尝试将 unicode 解码为 ascii,因此需要使用正确的编码格式来解码 unicode,即,utf-8
。
所以,你有:
Col_HTML = 19
HTML_Code = HTML_Code.decode('utf-8')
w_sheet.write(row_index, Col_HTML, str(HTML_Code))
关于python - 尝试使用 Python xlwt 保存 Excel 文件时出现 UnicodeDecodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25777754/