2020年5月26日

python pandas 写入文件报错’ascii’ codec can’t decode byte 0xe9 in position 0: ordin

作者 spoony

Traceback (most recent call last):
File “E:/excel.py”, line 59, in <module>
new_df.to_excel((department) + “.xls”, index=False, encoding=”gbk”) # ,)# department
File “C:\….lib\site-packages\pandas\core\generic.py”, line 2127, in to_excel
engine=engine)
File “C:\….lib\site-packages\pandas\io\formats\excel.py”, line 664, in write
writer.save()
File “C:\….lib\site-packages\pandas\io\excel.py”, line 1677, in save
return self.book.save(self.path)
File “C:\….lib\site-packages\xlwt\Workbook.py”, line 710, in save
doc.save(filename_or_stream, self.get_biff_data())
File “C:\….lib\site-packages\xlwt\Workbook.py”, line 674, in get_biff_data
shared_str_table = self.__sst_rec()
File “C:\….lib\site-packages\xlwt\Workbook.py”, line 636, in __sst_rec
return self.__sst.get_biff_record()
File “C:\….lib\site-packages\xlwt\BIFFRecords.py”, line 77, in get_biff_record
self._add_to_sst(s)
File “C:\….lib\site-packages\xlwt\BIFFRecords.py”, line 92, in _add_to_sst
u_str = upack2(s, self.encoding)
File “C:\….lib\site-packages\xlwt\UnicodeUtils.py”, line 50, in upack2
us = unicode(s, encoding)
UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe9 in position 0: ordinal not in range(128)

这个错误网上找了,解决办法根本没有用,实际上就是文件后缀的问题,与ascii码没有任何关系,pandas导出的excel后缀应当为xlsx,而不是xls。这样就没错了。留给需要的人吧。