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

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

错误提示:

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

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')
print('df=\n',df)
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-22-6c38b222d559> in <module>
      6 df = pd.DataFrame(arr,index=ind,columns=columns)
      7 print('df=\n',df)
----> 8 df.to_excel('pd-test-w.xls')
      9 print('df=\n',df)

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\_xlwt.py in __init__(self, path, engine, encoding, mode, **engine_kwargs)
     11     def __init__(self, path, engine=None, encoding=None, mode="w", **engine_kwargs):
     12         # Use the xlwt module as the Excel writer.
---> 13         import xlwt
     14 
     15         engine_kwargs["engine"] = engine

ModuleNotFoundError: No module named 'xlwt'
​

错误原因:

1、 提示没有安装xlwr模块,pip方式安装pandas时不会将xlwt作为依赖自动安装,需要手动安装xlwt模块 。如果要写入xlsx格式的excel文件,需要用到openpyxl模块,可以参考这篇文章:Python错误集锦:在pandas中用to_excel()写xlsx文件提示:ModuleNotFoundError: No module named ‘openpyxl’

解决方法:

1、 pip手动安装xlwt模块。

 pip install xlwt -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  -5  30 -28 -38 -9   6  33 -35 -13 -50
1  -1 -12 -48  24  7 -39 -43   4  15  38
2 -22  16  33  43  9  24  23  -5   6 -40


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

发表评论

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