Error message (posted for search indexing):
File "D:\Python\venv\lib\site-packages\openpyxl\worksheet\worksheet.py", line 664, in append
cell = Cell(self, row=row_idx, column=col_idx, value=content)
File "D:\Python\venv\lib\site-packages\openpyxl\cell\cell.py", line 116, in __init__
self.value = value
File "D:\Python\venv\lib\site-packages\openpyxl\cell\cell.py", line 215, in value
self._bind_value(value)
File "D:\Python\venv\lib\site-packages\openpyxl\cell\cell.py", line 194, in _bind_value
value = self.check_string(value)
File "D:\Python\venv\lib\site-packages\openpyxl\cell\cell.py", line 162, in check_string
raise IllegalCharacterError
openpyxl.utils.exceptions.IllegalCharacterError
According to the prompt, the solution found online is as follows:#
Replace illegal characters defined by openpyxl with empty characters, as shown below:
from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE
import openpyxl
import re
# Before writing, replace illegal characters with spaces
content = ILLEGAL_CHARACTERS_RE.sub(r'', content)
ws.cell(ridx, cidx).value = content
Here, ILLEGAL_CHARACTERS_RE.sub(r'', content)
only replaces the characters in the string. If you are writing list data and using .append()
to write, it is relatively difficult to filter out illegal characters.
At this time, you can modify the worksheet.py
file that the dependency relies on to solve the problem. Just click on the file mentioned in the error message.
The error occurs at line 664 in worksheet.py
, and content
happens to be present here. So now we just need to replace the illegal characters with empty characters in front.
The modified code is as follows:
Don't forget to include:
from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE