简体   繁体   English

使用openpyxl在Python中使用Excel命名范围

[英]Using Excel named ranges in Python with openpyxl

How do I loop through the cells in an Excel named range/defined name and set each cell value within the named range using openpyxl with Python 2.7? 如何在Excel命名范围/定义名称中循环遍历单元格,并使用带有Python 2.7的openpyxl将每个单元格值设置在指定范围内?

I found the following, but have not managed to get it to work for printing and setting the values of individual cells within the named range. 我找到了以下内容,但还没有设法让它用于打印和设置命名范围内的单个单元格的值。

Read values from named ranges with openpyxl 使用openpyxl从命名范围读取值

Here's my code so far, I have put in comments where I am looking to make the changes. 到目前为止,这是我的代码,我已经在评论中添加了我要进行更改的内容。 Thanks in anticipation. 谢谢你的期待。

    #accessing a named range called 'metrics' 
    namedRange = loadedIndividualFile.defined_names['metrics']

    #obtaining a generator of (worksheet title, cell range) tuples
    generator = namedRange.destinations

    #looping through the generator and getting worksheet title, cell range

    cells = []
    for worksheetTitle, cellRange in generator:
        individualWorksheet = loadedIndividualFile[worksheetTitle]

        #==============================
        #How do I set cell values here?
        # I am looking to print and change each cell value within the defined name range
        #==============================

        print cellRange
        print worksheetTitle
        #theWorksheet = workbook[worksheetTitle]
        #cell = theWorksheet[cellRange]

I managed to resolve it. 我设法解决了它。 Perhaps the following will be useful to someone else who is looking to access the values of each cell in a defined name or named range using openpyxl. 对于希望使用openpyxl访问定义名称或命名范围中每个单元格的值的其他人,以下内容可能会有用。

import openpyxl

wb = openpyxl.load_workbook('filename.xlsx') 
#getting the address 
address = list(wb.defined_names['metrics'].destinations)

#removing the $ from the address
for sheetname, cellAddress in address:
    cellAddress = cellAddress.replace('$','')

#looping through each cell address, extracting it from the tuple and printing it out     
worksheet = wb[sheetname]
for i in range(0,len(worksheet[cellAddress])):
    for item in worksheet[cellAddress][i]:
        print item.value`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM