2017-05-16 50 views
1

如何循環遍歷Excel命名的範圍/定義名稱中的單元格,並使用Python 2.7中的openpyxl設置命名範圍內的每個單元格值?使用Python中的Excel命名範圍和openpyxl

我發現了以下內容,但還沒有設法讓它在指定範圍內打印和設置單個單元格的值。

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] 
+0

你到底明白了什麼? –

+0

提取單個單元格值,但現在我已解決它,並將發佈解決方案以防其他人遇到同樣的問題。感謝您的關注。 – Py1001

回答

-1

我設法解決它。也許以下對於那些正在尋找使用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`