Openpyxl.utils.exceptions.IllegalcharacterError
Solution 1
Try this : This code works for me .
from openpyxl import *
book=Workbook ()
sheet=book.active
sheet.title="test"
x = 0
with open("temp.txt") as myfile :
text = myfile.readline()
while text !="":
sheet.cell (row=1,column=x+1).value=str(text).encode("ascii",errors="ignore")
x+=1
text = myfile.readline()
book.save ('test.xlsx')
Solution 2
I faced similar issue and found out that it is because of \xa1 character which is hex value of ascii 26 (SUB). Openpyxl is not allowing to write such characters (ascii code < 32). I tried xlsxwriter library without any issue it worte this character in xlsx file.
Solution 3
openpyxl
comes with an illegal characters regular expression, ready for you to use. Presuming you're happy to simply remove these characters, you can do:
import re
from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE
from openpyxl import *
book=Workbook ()
sheet=book.active
sheet.title="test"
for x in range (7729):
sheet.cell (row=1,column=x+1).value = ILLEGAL_CHARACTERS_RE.sub(r'',x)
book.save ('test.xlsx')
To speed it up, you could put the original cell value assignment inside a try/except and only run the re substitution when an openpyxl.utils.exceptions.IllegalCharacterError
is caught.
Source: https://www.programmersought.com/article/43315246046/
Related videos on Youtube
EHM
print("<{${H}} />") I like to keep an air of mystery about myself.
Updated on September 16, 2022Comments
-
EHM over 1 year
I have the following python code to write processed words into excel file. The words are about 7729
From openpyxl import * book=Workbook () sheet=book.active sheet.title="test" for x in range (7729): sheet.cell (row=1,column=x+1).value=x book.save ('test.xlsx')
This is the what the code I used looks like, but when I run it, it gives me an error that says
openpyxl.utils.exceptions.IllegalCharacterError
This is my first time using this module, I would appreciate any kind of help.
-
EHM about 6 yearsIn the real program x is a string what should I do for that, should I remove the int function and use the above
-
EHM about 6 yearsThank you so much but it seems this din't work. If this helps when I do like sheet ['A1']=1 or sheet ['A1']='hi' works.
-
toheedNiaz about 6 yearscan i see your sample data please ? and they way you are reading that data from the source ?
-
EHM about 6 years'Kitaabota', 'seenaa', 'yesuus',and yes i am reading it from a source and the source is a txt file.
-
toheedNiaz about 6 yearscan i see the code you are using to read the text file and exact one line for text file. that will help me to reproduce the issue
-
EHM about 6 yearsLet us continue this discussion in chat.