[英]Using Excel named ranges in Python with openpyxl
如何在Excel命名范圍/定義名稱中循環遍歷單元格,並使用帶有Python 2.7的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]
我設法解決了它。 對於希望使用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.