【发布时间】:2015-07-27 19:36:48
【问题描述】:
我正在尝试使用 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 位计算机上运行 Python 2.7。
【问题讨论】:
-
只是猜测,试试 -
# -*- coding: utf-8 -*-,而不是cp1252。 -
# coding...指令/注释只影响 Python 如何读取 源代码本身,而不会影响其运行方式。
标签: python unicode xlrd unicode-string