Openpyxl.utils.exceptions.IllegalcharacterError
Openpyxl.utils.exceptions.IllegalcharacterError
我有以下 python 代码将处理过的单词写入 excel 文件。字数约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')
这是我使用的代码的样子,但是当我 运行 它时,它给了我一个错误
openpyxl.utils.exceptions.IllegalCharacterError
这是我第一次使用这个模块,如果有任何帮助,我将不胜感激。
您错过了为单元格 sheet.cell (row=1,column=x+1).value =
添加值
像这样尝试
from openpyxl import *
book = Workbook ()
sheet = book.active
sheet.title = "test"
for x in range (7):
sheet.cell (row=1,column=x+1).value = "Hello"
book.save ('test.xlsx')
试试这个:
此代码对我有用。
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')
我遇到了类似的问题,发现这是因为 \xa1 字符是 ascii 26 (SUB) 的十六进制值。 Openpyxl 不允许写入此类字符(ascii 代码 < 32)。我尝试了 xlsxwriter 库,没有任何问题,它在 xlsx 文件中写入了这个字符。
openpyxl
自带非法字符正则表达式,随时可以使用。假设您愿意简单地删除这些字符,您可以这样做:
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')
为了加快速度,您可以将原始单元格值赋值放在 try/except 中,并且只有 运行 在捕获到 openpyxl.utils.exceptions.IllegalCharacterError
时重新替换。
我有以下 python 代码将处理过的单词写入 excel 文件。字数约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')
这是我使用的代码的样子,但是当我 运行 它时,它给了我一个错误
openpyxl.utils.exceptions.IllegalCharacterError
这是我第一次使用这个模块,如果有任何帮助,我将不胜感激。
您错过了为单元格 sheet.cell (row=1,column=x+1).value =
添加值
像这样尝试
from openpyxl import *
book = Workbook ()
sheet = book.active
sheet.title = "test"
for x in range (7):
sheet.cell (row=1,column=x+1).value = "Hello"
book.save ('test.xlsx')
试试这个: 此代码对我有用。
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')
我遇到了类似的问题,发现这是因为 \xa1 字符是 ascii 26 (SUB) 的十六进制值。 Openpyxl 不允许写入此类字符(ascii 代码 < 32)。我尝试了 xlsxwriter 库,没有任何问题,它在 xlsx 文件中写入了这个字符。
openpyxl
自带非法字符正则表达式,随时可以使用。假设您愿意简单地删除这些字符,您可以这样做:
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')
为了加快速度,您可以将原始单元格值赋值放在 try/except 中,并且只有 运行 在捕获到 openpyxl.utils.exceptions.IllegalCharacterError
时重新替换。