python - 在带有 openpyxl 的 Python 中使用 Excel 命名范围

标签 python python-2.7 openpyxl

如何使用带有 Python 2.7 的 openpyxl 遍历 Excel 命名范围/定义名称中的单元格并在命名范围内设置每个单元格值?

我发现了以下内容,但未能让它用于打印和设置指定范围内各个单元格的值。

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]

最佳答案

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

关于python - 在带有 openpyxl 的 Python 中使用 Excel 命名范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44002525/

相关文章:

Python:检查每小时的url请求

python - Airflow 依赖于过去的解释

python - 创建 wx.App 的多个实例 - 可以吗?

python - django 国家货币代码

python - 从 .h5 文件写入 excel : performance

javascript - 如何在递归生成的 <select> 下拉列表中附加回调?

python - python的交互式矢量图形 Canvas ?

python - 在不停止部分程序的情况下在 Python 2.7 中捕获警告

python - openpyxl 如何将单元格设置为 'ignore error'?

python - 在 python 中读取 .xlsx 格式