hengdin

导航

 
openpyxl.utils.exceptions.IllegalCharacterError

  • 原因
    Excel表中有非法字符,这些字符都是八进制的,需要进行清洗

  • 解决办法一:(自己亲测有效)

import re
def data_clean(text):
    # 清洗excel中的非法字符,都是不常见的不可显示字符,例如退格,响铃等
    ILLEGAL_CHARACTERS_RE = re.compile(r'[\000-\010]|[\013-\014]|[\016-\037]')
    text = ILLEGAL_CHARACTERS_RE.sub(r'', text)
    return text

df = df.fillna('').astype(str)
for col in df.columns:
    df[col] = df[col].apply(lambda x: data_clean(x))
df.to_excel(base_path + 'result.xlsx', index=False)

  • 解决办法二(该方法未测试,网站找到的):
import xlsxwriter
df.to_excel(base_path + 'result.xlsx', engine='xlsxwriter', index=False, encoding='utf-8')

posted on 2022-12-21 16:18  hengdin  阅读(3342)  评论(0编辑  收藏  举报