当dataframe存为excel时,报错openpyxl.utils.exceptions.IllegalCharacterError
说明你的数据集中存在着特殊字符。
定义如下的函数 来对文本数据进行处理,apply在可能出现特殊字符的列上,即可正产生成excel。还能定位出异常数据。
def get_IllegalCharacter(value):
# 定义文本编码 与 输入、输出文本编码保持一致
encoding = 'utf-8'
if value is None:
return
# convert to unicode string
if not isinstance(value, str):
# from openpyxl.compat import unicode
value = unicode(value, encoding)
value = unicode(value)
# string must never be longer than 32,767 characters
# truncate if necessary
value = value[:32767]
ILLEGAL_CHARACTERS_RE = re.compile(r'[\000-\010]|[\013-\014]|[\016-\037]')
if next(ILLEGAL_CHARACTERS_RE.finditer(value), None):
return '文本异常'
return value