当前位置:   article > 正文

pandas写入excel时报错openpyxl.utils.exceptions.IllegalCharacterError解决_pd.writeexcel openpyxl.utils.exceptions.illegalcha

pd.writeexcel openpyxl.utils.exceptions.illegalcharactererror规避

需求是要追加sheet写入原文件,所以engine还是得用openpyxl
写入文件前,用openpyxl的ILLEGAL_CHARACTERS_RE清除下不支持的字符

from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE
import pandas as pd


df = pd.read_excel(excel_filepath, sheet_name=sheet_name)

# do something

# 写入原文件前清除openpyxl不支持的字符
for col in df.columns:
    df[col] = df[col].apply(lambda x: ILLEGAL_CHARACTERS_RE.sub(r'', str(x) if not pd.isna(x) else ''))

with pd.ExcelWriter(excel_filepath, engine='openpyxl', mode='a') as writer:
    df.to_excel(writer, sheet_name='new sheet', index=False)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/209711
推荐阅读
相关标签
  

闽ICP备14008679号