Create named cells in multiple sheets with same name openpyxl

后端 未结 1 1098
感动是毒
感动是毒 2021-01-29 10:10

I am creating excel file with multiple sheets. In every sheet i need same define name with group of rows and columns.we can create it manually but through program how to achieve

相关标签:
1条回答
  • 2021-01-29 10:32

    I think the named ranges are global to the workbook, not local to each sheet. Which is hinted at by the error message you're getting:

    DefinedName with the same name and scope already exists

    So you'd have to give those different names

    wb = openpyxl.load_workbook(file.xlsx)
    sheet1 = wb['sheet1']
    sheet2 = wb['sheet2']
    wb.create_named_range('sales1', sheet1 , '$B$11:$B$35')
    wb.create_named_range('sales2', sheet2 , '$B$11:$B$35')
    

    or a more DRY solution:

    wb = openpyxl.load_workbook(file.xlsx)
    sheets = []
    for sheet_no in range(1,3):
        sheets[sheet_no] = wb[f'sheet{sheet_no}'] # note pre python 3.6 you should change f'sheet{sheet_no}' to 'sheet{}'.format(sheet_no)
        wb.create_named_range(f'sales{sheet_no}', sheets[sheet_no], '$B$11:$B$35')
    
    0 讨论(0)
提交回复
热议问题