在Python和openpyx中使用Excel命名范围

2024-10-01 09:32:52 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在Excel命名范围/定义名称中循环使用openpyxl和python2.7设置命名范围内的每个单元格值?在

我发现了以下内容,但还没有成功地使其用于打印和设置命名范围内各个单元格的值。在

Read values from named ranges with openpyxl

这是我目前为止的代码,我已经在我希望进行更改的地方添加了注释。谢谢你的期待。在

    #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]

Tags: cellrangegenerator命名namedmetricsvaluesprint
1条回答
网友
1楼 · 发布于 2024-10-01 09:32:52

我设法解决了。对于其他希望使用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`

相关问题 更多 >