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
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')