当前位置 博文首页 > RunningOnMyWay的博客:pandas无法创建excel文件或者无法读取exc

    RunningOnMyWay的博客:pandas无法创建excel文件或者无法读取exc

    作者:[db:作者] 时间:2021-06-10 09:14

    使用pandas,创建excel文件刚开始报错如下:
    Traceback (most recent call last):
      File "d:/sources/pythons/pandas/test.py", line 18, in <module>
        df.to_excel("people.xlsx")
      File "C:\Program Files\Python38\lib\site-packages\pandas\core\generic.py", line 2026, in to_excel
        formatter.write(
      File "C:\Program Files\Python38\lib\site-packages\pandas\io\formats\excel.py", line 730, in write
        writer = ExcelWriter(stringify_path(writer), engine=engine)
        from openpyxl.workbook import Workbook
    ModuleNotFoundError: No module named 'openpyxl'
    

    此时缺少对应的python模块openpyxl,使用以下命令安装即可:

    pip install openpyxl
    
    读取excel文件时报错:
      File "C:\Program Files\Python38\lib\site-packages\pandas\compat\_optional.py", line 110, in import_optional_dependency
        raise ImportError(msg) from None
    ImportError: Missing optional dependency 'xlrd'. Install xlrd >= 1.0.0 for Excel support Use pip or conda to install xlrd.
    

    除了安装对应的旧版本的xlrd(最新版本似乎不支持xlsx),还可以在读取excel文件代码中使用openpyxl,写法如下:

    people = pd.read_excel("people.xlsx", sheet_name="Sheet1",engine='openpyxl')