首页 > 解决方案 > 无法从 Python 3.6 读取 excel 文件

问题描述

我无法读取 excel 文件。我有 MS Excel 2016。

import pandas as pd

with open(r'dummy.xlsx','r') as exl:
  p = pd.ExcelFile(exl)
  print(p.sheet_names)


runfile('C:/Users/ESETPRI/Documents/My Python Scripts/pdf read.py', wdir='C:/Users/ESETPRI/Documents/My Python Scripts')
Traceback (most recent call last):

  File "<ipython-input-13-eb59316a92ec>", line 1, in <module>
runfile('C:/Users/ESETPRI/Documents/My Python Scripts/pdf read.py', wdir='C:/Users/ESETPRI/Documents/My Python Scripts')

  File "C:\Users\ESETPRI\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)

  File "C:\Users\ESETPRI\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/ESETPRI/Documents/My Python Scripts/pdf read.py", line 11, in <module>
p = pd.ExcelFile(exl)

  File "C:\Users\ESETPRI\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\excel.py", line 291, in __init__
data = io.read()

  File "C:\Users\ESETPRI\AppData\Local\Continuum\anaconda3\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]

UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 634: character maps to <undefined>

尝试了不同类型的编码 UTF-8、UTF-16、ASCII、CP1252 但没有成功。即使尝试使用空的 xlsx 文件,结果也相同。

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa4 in position 14: invalid start byte

UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 602-603: illegal encoding

UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 634: character maps to <undefined>

UnicodeDecodeError: 'ascii' codec can't decode byte 0xa4 in position 14: ordinal not in range(128)

编辑

也试过'latin-1'

 File "C:\Users\ESETPRI\AppData\Local\Continuum\anaconda3\lib\site-packages\xlrd\book.py", line 672, in get2bytes
return (BYTES_ORD(hi) << 8) | BYTES_ORD(lo)

 TypeError: unsupported operand type(s) for <<: 'str' and 'int'

标签: pythonexcelpython-3.xpandascsv

解决方案


文档尝试read_excel

>>> pd.read_excel('tmp.xlsx')
      Name  Value
0  string1      1
1  string2      2
2  string3      3

推荐阅读