【问题标题】:Is there a way to save data in named Excel cells using Python?有没有办法使用 Python 将数据保存在命名的 Excel 单元格中?
【发布时间】:2020-03-25 22:40:10
【问题描述】:

我在 Python 代码中使用 openpyxl 在 Excel 中输出值。但是,现在我发现自己处于 excel 文件中的单元格位置可能会根据用户而改变的情况。为了避免程序出现任何问题,我想命名代码可以将输出保存到的单元格。有什么方法可以让 Python 与 Excel 中的命名范围进行交互?

【问题讨论】:

    标签: python excel openpyxl


    【解决方案1】:

    为工作簿级别定义的名称

    import openpyxl
    wb = openpyxl.load_workbook("c:/tmp/SO/namerange.xlsx")
    ws = wb["Sheet1"]
    
    mycell = wb.defined_names['mycell']
    
    for title, coord in mycell.destinations:
        ws = wb[title]
        ws[coord] = "Update"    
    
    wb.save('updated.xlsx')
    print("{} {} updated".format(ws,coord))
    
    

    【讨论】:

      【解决方案2】:

      我能够使用defined_names 找到命名范围的参数。之后我就像一个普通的 Excel 单元格一样工作。

      from openpyxl import load_workbook
      
      openWB=load_workbook('test.xlsx')
      
      rangeDestination = openWB.defined_names['testCell']
      print(rangeDestination)
      sheetName=str(rangeDestination.attr_text).split('!')[0]
      cellName = str(rangeDestination.attr_text).split('!')[1]
      
      sheetToWrite=openWB[sheetName]
      cellToWrite=sheetToWrite[cellName]
      sheetToWrite[cellName]='TEST-A3'
      print(sheetName)
      print(cellName)
      
      openWB.save('test.xlsx')
      openWB.close()
      
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-20
        • 2020-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多