将Python中的Excel命名范围与openpyxl一起使用
如何使用openpyxl和Python 2.7循环遍历Excel命名范围/定义名称中的单元格,并设置命名范围内的每个单元格值 我发现了以下内容,但未能使其在命名范围内打印和设置单个单元格的值 这是到目前为止我的代码,我已经在注释中添加了我希望进行更改的地方。谢谢你的期待将Python中的Excel命名范围与openpyxl一起使用,python,python-2.7,openpyxl,Python,Python 2.7,Openpyxl,如何使用openpyxl和Python 2.7循环遍历Excel命名范围/定义名称中的单元格,并设置命名范围内的每个单元格值 我发现了以下内容,但未能使其在命名范围内打印和设置单个单元格的值 这是到目前为止我的代码,我已经在注释中添加了我希望进行更改的地方。谢谢你的期待 #accessing a named range called 'metrics' namedRange = loadedIndividualFile.defined_names['metrics']
#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`
你到底不明白什么?提取单个单元格的值,但我现在已经解决了它,并将发布解决方案,以防其他人有同样的问题。谢谢你的关注。底部的三分之一应该缩进吗?这在2020年对我很有帮助。谢谢你回答自己的问题!