【问题标题】:UnicodeDecodeError when trying to save an Excel File with Python xlwt尝试使用 Python xlwt 保存 Excel 文件时出现 UnicodeDecodeError
【发布时间】:2014-09-11 01:47:55
【问题描述】:

我正在运行一个 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 是什么对象?也许 str() 是将其转换为字符串的错误方法。请改用 unicode()。

标签: python excel unicode ascii xlwt


【解决方案1】:

在将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))

【讨论】:

    猜你喜欢
    • 2014-03-11
    • 1970-01-01
    • 2016-04-17
    • 2017-12-10
    • 2019-08-08
    • 1970-01-01
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多