簡體   English   中英

在 Python 中,是否有一個庫可以根據其名稱設置/更新一個 Excel 單元的值?

[英]In Python, is there a library to set/update the value of one Excel cell based on its name?

我有一個包含幾個命名單元的 Excel 文件。 我想用新值更新這些單元格。 而不是使用坐標: worksheet["D3"] = "New Excel Value" 我想用它的命名值設置它: worksheet["cell name"] = "New Excel Value"

我所看到的是xlwings有一個 function 來根據其命名值設置單元格。 但是xlwings需要在機器上安裝Excel,我們的機器不是這樣。 因此我在看openpyxl。 我已經看到了有效的解決方案,例如12 兩者都需要額外的 function 和一些手動步驟來檢索單個命名單元。 我希望以與帶有方括號的法線坐標相同的方式查看檢索。 這讓我覺得我錯過了文檔中的某些內容。

因此我想知道,設置命名單元格值的最佳方法是“ Is there a way to save data in named Excel cells using Python? openpyxl中提出的解決方案?

- 編輯 -

我能想到的最好的就是下面的代碼片段。 我會把它貼在這里,以防它對任何人有幫助:

    def _set_value_for_excel_named_cell(self, cell_name: str, value: Any) -> None:
    """Sets a value for the Excel cell based on its name."""
    worksheet_title, cell_coordinates = list(
        self._workbook.defined_names[cell_name].destinations
    )[0]
    self._workbook[worksheet_title][cell_coordinates] = value

您可以創建自己的 class 並使用setitemgetitem方法通過包裝 openpyxl 自己創建該接口。 使用您已經鏈接到的資源,我創建了一個工作示例來幫助您入門。

from openpyxl import load_workbook

filename = "test.xlsx"


class XLWrap:
    def __init__(self, wb):
        self.wb = wb

    def __getitem__(self, key):
        # Returns the value for cells given set name
        return [
            self.wb[sheet][cell].value
            for sheet, cell in list(self.wb.defined_names[key].destinations)
        ]

    def __setitem__(self, key, dat):
        # Sets the value for cells in workbook given set name
        cells = self.wb.defined_names[key].destinations
        for sheet, cell in cells:
            ws = self.wb[sheet]
            ws[cell] = dat
        self.save()

    def save(self):
        self.wb.save(filename)


wb = load_workbook(filename)
xlw = XLWrap(wb)
print(xlw["test"])
xlw["test"] = "named_cell_val_after"
print(xlw["test"])

Output:

['named_cell_val_before']
['named_cell_val_after']

以上不適用於一系列單元格。 可以為文檔中注明的命名范圍創建一個包裝器來處理不同類型的 output。

它們的定義非常松散。 它們可能包含一個常數、一個公式、一個單元格引用、一個單元格區域或跨不同工作表的多個單元格區域。 或以上所有。

所以相關的實現將取決於你如何使用它們。 對於單元格范圍,我有這個快速而骯臟的工作示例,如果您有單個單元格定義,它很快就會崩潰:

def __getitem__(self, key):
    # Returns the value for cells given set name
    sheets = [
        self.wb[sht][rng]
        for sht, rng in list(self.wb.defined_names[key].destinations)
    ]
    values = []
    for sheet in sheets:
        for row in sheet:
            for cell in row:
                values.append(cell.value)
    return values

def __setitem__(self, key, dat):
    # Sets the value for cells in workbook given set name
    sheets = [
        self.wb[sht][rng]
        for sht, rng in list(self.wb.defined_names[key].destinations)
    ]
    for sheet in sheets:
        for row in sheet:
            for cell in row:
                cell.value = dat
    self.save()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM