問題:
在使用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
中添加: