Python错误集锦:在pandas中用to_excel()写xlsx文件提示:ModuleNotFoundError: No module named ‘openpyxl’

原文链接:http://www.juzicode.com/archives/3128

错误提示:

在pandas中用to_excel()写xlsx文件时提示:ModuleNotFoundError: No module named ‘openpyxl’:

import numpy as np
import pandas as pd
arr = np.random.randint(-50,50,size=(3,10))
ind = [x for x in range(3)]
columns = list('ABCDEFGHIJ')
df = pd.DataFrame(arr,index=ind,columns=columns)
print('df=\n',df)
df.to_excel('pd-test-w.xlsx') #这里是xlsx文件,不行xls文件
print('df=\n',df)
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-25-23a12bb507d4> in <module>
      6 df = pd.DataFrame(arr,index=ind,columns=columns)
      7 print('df=\n',df)
----> 8 df.to_excel('pd-test-w.xlsx')

d:\python\python38\lib\site-packages\pandas\core\generic.py in to_excel(self, excel_writer, sheet_name, na_rep, float_format, columns, header, index, index_label, startrow, startcol, engine, merge_cells, encoding, inf_rep, verbose, freeze_panes)
   2024             inf_rep=inf_rep,
   2025         )
-> 2026         formatter.write(
   2027             excel_writer,
   2028             sheet_name=sheet_name,

d:\python\python38\lib\site-packages\pandas\io\formats\excel.py in write(self, writer, sheet_name, startrow, startcol, freeze_panes, engine)
    728             need_save = False
    729         else:
--> 730             writer = ExcelWriter(stringify_path(writer), engine=engine)
    731             need_save = True
    732 

d:\python\python38\lib\site-packages\pandas\io\excel\_openpyxl.py in __init__(self, path, engine, mode, **engine_kwargs)
     16     def __init__(self, path, engine=None, mode="w", **engine_kwargs):
     17         # Use the openpyxl module as the Excel writer.
---> 18         from openpyxl.workbook import Workbook
     19 
     20         super().__init__(path, mode=mode, **engine_kwargs)

ModuleNotFoundError: No module named 'openpyxl'

错误原因:

1、 提示没有找到openpyxl模块,pip方式安装pandas时不会将 openpyxl 作为依赖自动安装,需要手动安装 openpyxl 模块 。“xlsx”格式的excel文件需要用到openpyxl模块。这个错误和写入”xls”格式的文件类似,xls格式的excel文件需要用到xlwt模块,参考这里:Python错误集锦:在pandas中用to_excel()写xls文件提示:ModuleNotFoundError: No module named ‘xlwt’

解决方法:

1、 pip手动安装 openpyxl 模块。

 pip install openpyxl -i https://pypi.tuna.tsinghua.edu.cn/simple
import numpy as np
import pandas as pd
arr = np.random.randint(-50,50,size=(3,10))
ind = [x for x in range(3)]
columns = list('ABCDEFGHIJ')
df = pd.DataFrame(arr,index=ind,columns=columns)
print('df=\n',df)
df.to_excel('pd-test-w.xls')
df=
     A   B   C   D   E   F   G   H   I   J
0  39 -50 -21  -5  37 -27 -48 -48  35  45
1 -39  -4  -6 -25  -6   4  46 -12  25   9
2  11  -2 -16   4 -29 -26  26 -32 -39  -8

关注微信公众号:“桔子code”,欢迎后台留言撩我,我会尽我所能为你解惑Python,C等编程知识

发表评论

电子邮件地址不会被公开。 必填项已用*标注