如何在 Python 中的特定单元格值之前插入空白行?

How do I insert a blank row before specific cell values in Python?

我正在使用图书馆 Openpyxl

我有 15 个函数,它们看起来与下面的函数相同,只是字符串不同。我试过将它们组合成一个函数,但这只会使整个 sheet 行成为空白。到目前为止,我发现的唯一方法是为其中的每一个设置一个单独的函数,并在其中进行中断。

这是唯一的方法还是有更简单、更有效的方法?

import openpyxl

pws = openpyxl.load_workbook(filepath.xlsx)
pws_sheet = pws['Sheet']

def ans_call_by_agent():
    flag=False
    for row in pws_sheet.iter_rows():
        for cell in row:
            if cell.value == 'Ans. Call Distribution by Agent':
                pws_sheet.insert_rows(cell.row, amount=1)
                pws.create_sheet('Ans. Call by Agent')
                flag=True
        if flag:break
        else:
            continue
def all_calls_by_hour():
    flag=False
    for row in pws_sheet.iter_rows():
        for cell in row:
            if cell.value == 'All Call Distribution by Hour':
                pws_sheet.insert_rows(cell.row, amount=1)
                pws.create_sheet('All Calls by Hour')
                flag=True
        if flag:break
        else:
            continue
#call blank row functions
ins_agent_availability_detail()
ins_agent_missed_calls()
ins_all_calls_by_day()
ins_all_calls_by_day_of_week()
ins_all_calls_by_hour()
ins_all_calls_by_queue()
ins_all_service_level()
ins_ans_calls_agent()
ins_ans_calls_by_queue()
ins_ans_call_detail()
ins_ans_service_level()
ins_call_disconnection_cause()
ins_unans_calls_by_queue()
ins_unans_call_detail()
ins_unans_service_level()

单函数尝试如下,只在sheet的顶部添加一个空行,然后停止。

def ans_calls_by_agent():
    #flag=False
    for row in pws_sheet.iter_rows():
        for cell in row:
            if cell.value == 'Ans. Call Distribution by Agent':
                pws_sheet.insert_rows(cell.row, amount=1)
                pws.create_sheet('Ans. Call by Agent')
                pws_sheet.delete_rows(cell.row, amount=1)
            elif cell.value == 'All Call Distribution by Hour':
                pws_sheet.insert_rows(cell.row, amount=1)
                pws.create_sheet('All Calls by Hour')
                pws_sheet.delete_rows(cell.row, amount=1)
            #flag=True
        #if flag:break
        else:
            continue

如果我注释掉标志行并添加 pws_sheet.delete_rows(cell.row,amount=1) 那么它会继续,但只有当 cell.value 被删除时,我宁愿这不是解决方案。

有;

def ans_calls_by_agent(compare_val, create_name):
    for row in pws_sheet.iter_rows():
        for cell in row:
            if cell.value == compare_val:
                pws_sheet.insert_rows(cell.row, amount=1)
                pws.create_sheet(create_name)
                pws_sheet.delete_rows(cell.row, amount=1)
                break

不工作?

flag的逻辑是多余的。在您的第二个示例中,您还将 flag=True 部分放在 if 语句之外,因此它将始终设置为 True,您可能不希望这样。