openpyxl.utils.exceptions.IllegalCharacterError报错有效解决方案

问题:

在使用openxyl写入excel的时候,可能会出现openpyxl.utils.exceptions.IllegalCharacterError的提示错误 。根据提示可以知道是openpyxl模块中的错误。
openpyxl.utils.exceptions.IllegalCharacterError报错有效解决方案_第1张图片

解决方案:

进入报错路径,查看cell.py文件,找到报错位置

    def check_string(self, value):
        """Check string coding, length, and line break character"""
        if value is None:
            return
        # convert to str string
        if not isinstance(value, str):
            value = str(value, self.encoding)
        value = str(value)
        # string must never be longer than 32,767 characters
        # truncate if necessary
        value = value[:32767]
        if next(ILLEGAL_CHARACTERS_RE.finditer(value), None):
            raise IllegalCharacterError
        return value

其中ILLEGAL_CHARACTERS_RE的定义在文件的开头,如下:

ILLEGAL_CHARACTERS_RE = re.compile(r'[\000-\010]|[\013-\014]|[\016-\037]')

可以看出,这里面的非法字符都是八进制,可以到对应的ASCII表中查看,的确都是不常见的不可显示字符,例如退格,响铃等,在此处被定义为excel中的非法字符。

既然检测到excel中存在[\000-\010]|[\013-\014]|[\016-\037]这些非法的字符,因此可以将要写入的字符串中的非法字符替换掉,再重新写入excel即可。如下:

① 在自己的代码开头添加:

import re

ILLEGAL_CHARACTERS_RE = re.compile(r'[\000-\010]|[\013-\014]|[\016-\037]')

② 在所要写入excel的字符串text中添加:

text = ILLEGAL_CHARACTERS_RE.sub(r'', text)

再次运行,报错解决!

你可能感兴趣的:(报错类,python)