I am trying to apply conditional formatting to my workbook which has multiple sheets but the below code will not work. I need a loop which will go through each sheet but when I run it, it doesnt recongise sheet 1.
#Apply % bars to the column.
sheet_name = ['sheet1', 'sheet2', 'sheet3', 'sheet4']
for n in range(0,len(sheet_name),1):
ws = writer.sheets[sheet_name[n]]
ws.conditional_format('H2:H100', {'type': 'data_bar',
#'bar_solid': True})
writer.save()
将writer.save()
放入循环中,
The OP ( debugging-mode ) script produces below print result:
sheet_name = ['sheet1', 'sheet2', 'sheet3', 'sheet4']
# code OP.
for n in range(0,len(sheet_name),1):
print (n) # debugging to see what happens here.
x = [sheet_name[n]]
print (x) # and see what this does.
... snippet code....
And prints the following:
0 # n0
['sheet1'] # x
1 # n1
['sheet2'] # x
2 # n2
['sheet3'] # x
3 # n3
['sheet4'] # x
There are two flavors to get your sheetname and sheetnumber correct for input in the ws = ..code
:
sheet_name = ['sheet1', 'sheet2', 'sheet3', 'sheet4']
for sheet in sheet_name:
# option 1 to get sheetname and sheet number
sheetname = ''
sheetnumber = ''
for x in sheet:
print (x) # opt.1 print 1
if x is not int:
sheetname +=x
else:
sheetnumber + x
print (sheetname, sheetnumber) # opt.1 print 2
# option 2 to get sheetname and sheet number
name, value = sheet[0:5], sheet[5:]
print (name, value)
# ... your code ...continues here with linked option 1 or 2.
# ws = writer.sheets[sheet_name[n]]
# ws.conditional_format('H2:H100', {'type': 'data_bar',
#'bar_solid': True})
#writer.save() # <-- check if...
...user Carsten is correct about indentation for this!!
The printed result from both options:
s # opt.1 ..print 1
h
e
e
t
1
sheet1 # opt.1 ..print 2
sheet 1 # opt.2
s # opt.1 ..print 1
h
e
e
t
2
sheet2 # opt.1 ..print 2
sheet 2 # opt.2
...snippet ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.