Minxio

Minxio

人生如逆旅,我亦是行人。

openpyxl encountered an openpyxl.utils.exceptions.IllegalCharacterError error while writing.

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

image-20221221121108546

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.

image-20221221122149059

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.

image-20221221122458811

The modified code is as follows:

image-20221221122856867

Don't forget to include:

from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.