无法从Python 3.6读取Excel文件

时间:2018-07-18 06:09:39

标签: python excel python-3.x pandas csv

我无法读取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'

2 个答案:

答案 0 :(得分:0)

docs尝试read_excel

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

答案 1 :(得分:0)

尝试

和熊猫一起

workbook_df=pd.ExcelFile(input_file_path)
key_sheet = workbook_df.parse("KEY")

使用openpyxl

wb = openpyxl.load_workbook(input_file_path)
write_output = wb.get_sheet_by_name('OUTPUT')