Pandas read_excel() 导入 xlrd 失败

Pandas read_excel() fails on importing xlrd

我想将文件夹中存储的多个 .xls 文件转换为 .csv 格式。到目前为止,这是我得到的:

import glob
import os
import csv
import pandas as pd

path = r'C:\Users\XXX\Desktop\Test'
full_path = os.path.join(path, '*.xls')

    for filename in glob.glob(full_path):

        name_xls = os.path.basename(filename)
        name_csv = name_xls.replace('.xls', '.csv')

        data_xls = pd.read_excel(name_xls)
        data_xls.to_csv(name_csv, sep=';', encoding='ASCI')

即使我下载了 pandas 和 xlrd 库,我仍然收到以下错误:

Traceback (most recent call last):   File
"C:\Users\XXX\.thonny\BundledPython36\lib\site-packages\pandas\io\excel.py",
line 261, in __init__
  **import xlrd ModuleNotFoundError: No module named 'xlrd'**

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File
"C:\Users\XXX\Desktop\coverage_code_0\coverage_code_0.py", line
16, in <module>
  data_xls = pd.read_excel(name_xls)   File  
C:\Users\XXX\.thonny\BundledPython36\lib\site-packages\pandas\util\_decorators.py",
line 118, in wrapper
  return func(*args, **kwargs)   File "C:\Users\XXX\.thonny\BundledPython36\lib\site-packages\pandas\io\excel.py",
line 230, in read_excel
  io = ExcelFile(io, engine=engine)   File "C:\Users\XXX\.thonny\BundledPython36\lib\site-packages\pandas\io\excel.py",
line 263, in __init__
  raise ImportError(err_msg) ImportError: Install xlrd >= 0.9.0 for Excel support

import xlrd 不起作用,当我包含那个编译器时说:

No module named 'xlrd'

我认为我的代码中有错误,但我不知道在哪里。有什么想法吗?

你需要 运行 pip install xlrd 在你有 pandas 的同一个解释器和 virutalenv 中。在你的评论中你说你有 xlrd 安装在 c:\users\XXX\appdata\local\programs\python\python36-32,但你的 pandas 在 C:\Users\XXX\.thonny\BundledPython36\ 中。如果您不使用 virtualenv,请尝试在 BundledPython36 文件夹中找到 pip 并 运行 它。

C:\Users\XXX\.thonny\BundledPython36\...\pip install xlrd

如果你使用 virtualenv,activate it 并且只是 运行 pip install xlrd

如果你这样做,你需要这个包:

def convert_to_csv():
    PATH = path_to_excel
    fileNames = os.listdir(PATH)
    fileNames = [file for file in fileNames if '.xls' in file]
    for file in fileNames: 
        exl =  pd.read_excel(PATH+file)
        exl.to_csv(PATH+file[:-3]+'csv',sep=';', index=False, header=True)
if __name__ == "__main__":
    import pandas as pd
    convert_to_csv()