Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Openpyxl-在另一个文件中使用导入的函数_Python_Excel_Openpyxl - Fatal编程技术网

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

Python Openpyxl-在另一个文件中使用导入的函数,python,excel,openpyxl,Python,Excel,Openpyxl,我有一个包含多个工作表的工作簿,我希望在每个工作表上运行相同的函数。 为了获得更清晰的代码,我将工作簿表拆分为不同的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,

我有一个包含多个工作表的工作簿,我希望在每个工作表上运行相同的函数。 为了获得更清晰的代码,我将工作簿表拆分为不同的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和其他sheet(sheet_3.py…)上运行

如果我现在这样做,我该怎么做

>>>sheet_2.py
from sheet_1 import addTitle
addTitle()
这将在sheet_1.py而不是sheet_2.py上运行addTitle

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


提前谢谢

您只需在一个
.py
文件中打开工作簿,并在其上的所有工作表中进行迭代即可。实际上,不需要在单独的脚本上运行它

openpyxl中有一个名为
.get\u sheet\u 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
脚本,它可以完成您需要的所有操作。

是的,但我这样做是因为每个工作表上运行着几个不同的函数,为了进行适当的修改,我必须单独保存这些脚本。此外,我只需要在几张工作表上运行此函数,而不是在每张工作表上运行。您可以设置要运行的工作表列表,并在
for
语句中使用它。