Create named cells in multiple sheets with same na

2019-03-06 18: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 this.

Below is the code:

wb = openpyxl.load_workbook(file.xlsx)
shee1 = wb['sheet1']
shee2 = wb['sheet1']
wb.create_named_range('sales', shee1 , '$B$11:$B$35')
wb.create_named_range('sales', shee2 , '$B$11:$B$35')

following is the error i am getting

File "C:\Users\728355\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\workbook\workbook.py", line 319, in create_named_range self.defined_names.append(defn) File "C:\Users\728355\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\workbook\defined_name.py", line 201, in append raise ValueError("""DefinedName with the same name and scope already exists""") ValueError: DefinedName with the same name and scope already exists

回答1:

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