使用xlwt在Excel中冻结单元格

9

我正在动态创建工作表,并不给它们命名。我无法冻结第一列和第一行,我尝试过在添加到工作簿时给工作表命名,这样可以实现。但是对于动态创建的工作表来说并不起作用。以下是代码:

base = xlwt.Workbook()
for k,v in MainDict.items():
    base.add_sheet(k.upper())
    col_width = 256 * 50
    xlwt.add_palette_colour("custom_colour", 0x21)
    pattern = 'url:(.*)'
    search = re.compile(pattern)
    base.set_colour_RGB(0x21, 251, 228, 228)
    style = xlwt.easyxf('pattern: pattern solid, fore_colour custom_colour;font : bold on;alignment: horiz center;font: name Times New Roman size 20;font:underline single')
    index = MainDict.keys().index(k)
    ws = base.get_sheet(index)
    ws.set_panes_frozen(True)
    try:
        for i in itertools.count():
            ws.col(i).width = col_width
    except ValueError:
        pass
    style1 = xlwt.easyxf('font: name Times New Roman size 15')
    style2 = xlwt.easyxf('font : bold on;font: name Times New Roman size 12')
    col=0
    for sk in MainDict[k].keys():
        ws.write(0,col,sk.upper(),style)
        col+=1
        row =1
        for mk in MainDict[k][sk].keys():
            for lk,lv in MainDict[k][sk][mk].items():
                for items in lv:
                    text = ('%s URL: %s')%(items,lk)
                    links =('No data Found. Please visit the URL: %s')% (lk)
                    url = re.findall(pattern,text)
                    if len(items) != 0:
                        if re.match(pattern,text)==True:
                            ws.write(row,col-1,url,style2)
                        else:                       
                            ws.write(row,col-1,text,style1)
                            row+=1
                    else:
                        ws.write(row,col-1,links,style2)
                     #ws.Column(col-1,ws).width = 10000
                        row+=1
default_book_style = base.default_style
default_book_style.font.height = 20 * 36
base.save('project7.xls')

我认为的是,只有在保存整个工作簿之前,工作表才不会被冻结。请尝试保存整个工作簿。 - sgp
如果我的回答有帮助,请确认一下,这样其他人也能轻松地找到这个答案。谢谢! - Stephen Lin
2个回答

15
你必须使用

    ws.set_panes_frozen(True)
    ws.set_horz_split_pos(1) 
    ws.set_vert_split_pos(1) 
为使冷冻生效。

3
这不起作用的原因可能是“get_sheet()”函数的结果。相反,将“add_sheet()”调用存储到“ws”中并使用它:
#base.add_sheet(k.upper())
ws = base.add_sheet(k.upper())

然后,您需要使用以下属性序列来冻结顶行:
#ws = base.get_sheet(index)
#ws.set_panes_frozen(True)
ws.set_horz_split_pos(1)
ws.set_vert_split_pos(1)
ws.panes_frozen = True
ws.remove_splits = True

我使用你的代码片段进行了测试,它在我的端上可以正常工作。
供参考,你可以通过函数设置这些属性,也可以通过赋值方式设置:
ws.set_panes_frozen(True)
ws.set_remove_splits(True)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接