Solution
For style setting functions:
def define_style():
font = xlwt.Font()
font.colour_index = 1
my_style = xlwt.XFStyle()
my_style.font = font
return my_style
When writing data, do not use sheet.write (0, 0, 'data', define)_ Style ()) in this way, change to:
mystyle = define_style()
sheet.write(0, 0, 'data', mystyle)
Example analysis
The following code will report an error
import xlwt
def define_style():
font = xlwt.Font()
font.colour_index = 1
my_style = xlwt.XFStyle()
my_style.font = font
return my_style
if __name__ == '__main__':
book = xlwt.Workbook(encoding='utf-8')
sheet = book.add_sheet('sheet1', cell_overwrite_ok=True)
# mystyle = define_style()
for i in range(10000):
sheet.write(i, 0, u'(0,0)', define_style())
book.save('my_excel.xlsx')
Modify the part in main function as follows:
mystyle = define_style()
for i in range(10000):
sheet.write(i, 0, u'(0,0)', mystyle)
Reason analysis
When using xlwt to write data, when passing in the style of xfstyle format, do not use anonymous function to call to write, otherwise after writing 4094 data, it will exceed the threshold, and an error will be reported: valueerror: more than 4094 XFS (styles)