问题:
在使用openxyl写入excel的时候,可能会出现
openpyxl.utils.exceptions.IllegalCharacterError
的提示错误 。根据提示可以知道是openpyxl模块中的错误。
解决方案:
进入报错路径,查看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
的定义在文件的开头,如下:
可以看出,这里面的非法字符都是八进制,可以到对应的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
中添加: