Openpyxl - 在另一个文件中使用导入的函数

Openpyxl - Use imported function in another file

我有一个包含多个 sheet 的工作簿,我想在每个 sheet 上 运行 使用相同的功能。 为了获得更简洁的代码,我将工作簿 sheet 拆分为不同的 python 模块。

在文件 sheet_1.py 中,我有以下功能:

>>>sheet_1.py
#This adds the text "Month: April" in the last row, first column cell
def addTitle():
    for col in ws2.iter_cols(min_row=ws2.max_row, max_row=ws2.max_row, min_col=1, max_col=1):
        for cell in col:
            cell.value = "Month: April"

    wb2.save(destination)
    wb2.close()

我想在 sheet_2.py 和其他 sheets (sheet_3.py.. .)

如果我执行以下操作,现在我该如何执行此操作:

>>>sheet_2.py
from sheet_1 import addTitle
addTitle()

这将 运行 在 sheet_1.py 上添加标题而不是 sheet_2.py

我敢肯定,我在这里遗漏了一些东西...

提前致谢!!

您可以只在一个 .py 文件中打开您的工作簿,然后遍历其中的所有工作表。实际上不需要 运行 它在单独的脚本上。

openpyxl 中有一个方法叫做.get_sheet_names()。使用它来获取工作簿中所有工作表的列表并遍历它:

list_of_sheets = wb.get_sheet_names()
for sheet in list_of_sheets:
ws = wb[sheet]
    for col in ws.iter_cols(min_row=ws.max_row, max_row=ws.max_row, min_col=1,   max_col=1):
        for cell in col:
            cell.value = "Month: April"

最后,您将拥有一个独特的 .py 脚本,可以满足您的所有需求。