[英]“UnicodeEncodeError: 'charmap' codec can't encode characters” when trying to parse .xlsx by openpyxl
--- update --- - 更新 -
I think this console log nails the issue, however it's still not clear how to fix it: 我认为此控制台日志解决了该问题,但是仍不清楚如何解决此问题:
>>> workbook = openpyxl.load_workbook('data.xlsx')
>>> worksheet = workbook.active
>>> worksheet['A2'].value
u'\u041c\u0435\u0448\u043e\u043a \u0434\u0435\u043d\u0435\u0433'
>>> print worksheet['A2'].value
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\encodings\cp437.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-4: character maps to <undefined>
--- end update --- - 结束更新 -
I'm trying to print the values of some .xlsx cells using openpyxl: 我正在尝试使用openpyxl打印一些.xlsx单元格的值:
import openpyxl
workbook = openpyxl.load_workbook(filename='puzzles.xlsx')
worksheet = workbook.active
for row in worksheet.iter_rows('A2:K5'):
print row[0].value
Which results in the following error: 导致以下错误:
Traceback (most recent call last):
File "xls_import.py", line 8, in <module>
print row[0].value
File "C:\Python27\lib\encodings\cp437.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-4: character maps to <undefined>
As far as I know, XLSX is encoded as UTF-8, however: 据我所知,XLSX被编码为UTF-8,但是:
print row[0].value.decode('utf-8')
does not help either: 也无济于事:
Traceback (most recent call last):
File "xls_import.py", line 8, in <module>
print row[0].value.decode('utf-8')
File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)
Any suggestions? 有什么建议么?
I'm running Python 2.7 and openpyxl 2.2.5. 我正在运行Python 2.7和openpyxl 2.2.5。
openpyxl返回unicode字符串(XML本身以UTF-8编码),因此您无需对其进行解码 (从编码到unicode的解码),而是以您选择的编码对其进行编码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.