如何遍历每个Excel工作表名称

时间:2019-03-23 21:08:27

标签: python excel formatting

我正在尝试将条件格式应用于我的工作簿,该工作簿有多个工作表,但是下面的代码不起作用。我需要一个遍历每张纸的循环,但是当我运行它时,它不会使第一张纸变硬。

#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()

2 个答案:

答案 0 :(得分:0)

writer.save()放入循环中,

答案 1 :(得分:0)

OP(调试模式)脚本产生以下打印结果:

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....

并打印以下内容:

0                # n0
['sheet1']       # x
1                # n1
['sheet2']       # x
2                # n2
['sheet3']       # x
3                # n3
['sheet4']       # x

有两种方法可以使工作表名称和工作表号正确输入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...

...用户Carsten对于缩进是正确的!

两个选项的打印结果:

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 ...