我正在尝试用xlrd读取一个.xlsx。我把一切都安排好了工作。它适用于正常英文字母和数字的数据。然而,当它转到瑞典字母(奥奥)时,它给出了这个错误:
print str(sheet.cell_value(1, 2)) + " " + str(sheet.cell_value(1, 3)) + " " + str(sheet.cell_value(1, 4)) + " " + str(sheet.cell_value(1, 5))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xd6' in position 1: ordinal not in range(128)我的代码:
# -*- coding: cp1252 -*-
import xlrd
file_location = "test.xlsx"
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(0)
print str(sheet.cell_value(1, 2)) + " " + str(sheet.cell_value(1, 3)) + " " + str(sheet.cell_value(1, 4)) + " " + str(sheet.cell_value(1, 5))我甚至试过:
workbook = xlrd.open_workbook("test.xlsx", encoding_override="utf-8")以及:
workbook = xlrd.open_workbook("test.xlsx", encoding="utf-8")编辑:我在Windows 7 64位计算机上运行Python2.7.
发布于 2015-07-27 20:03:56
‘'ascii’编解码器不能编码
这里的问题不是读取文件时的解码,而是打印所需的编码。您的环境正在为sys.stdout使用ASCII,所以当您试图打印任何无法在ASCII中编码的Unicode字符时,您将收到该错误。
字符编码与平台有关。在Windows下,如果流是交互式的(也就是说,如果它的isatty()方法返回True),则使用控制台代码页,否则使用ANSI代码页。在其他平台下,使用区域编码(请参见locale.getpreferredencoding())。 但是,在所有平台下,可以通过在启动Python之前设置PYTHONIOENCODING环境变量来重写此值。
发布于 2016-03-16 17:13:07
默认情况下,xlrd使用Unicode编码。如果xlrd无法识别编码,那么它将考虑excel文件中使用的编码是ASCII,字符编码。最后,如果编码不是ASCII,或者python无法将数据转换为Unicode,那么它将引发UnicodeDecodeError。
别担心,我们有办法解决这类问题。您似乎正在使用cp1252。因此,当您使用open_workbook()打开文件时,您可以按如下方式调用它:
>>> book = xlrd.open_workbook(filename='filename',encoding_override="cp1252")当您使用上面的函数时,xlrd将对相应的编码进行解码,这样就更好了。
资料来源:
发布于 2015-07-27 20:34:57
在打印之前,尝试使用utf-8作为@Anand S Kumar建议的字符串和decode字符串。
# -*- coding: utf-8 -*-
import xlrd
file_location = "test.xlsx"
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(0)
cells = [sheet.cell_value(1, i).decode('utf-8') for i in range(2, 6)]
print ' '.join(cells)https://stackoverflow.com/questions/31661769
复制相似问题