如何使用pythonxlwings在excel工作簿中检测受保护的工作表?

2024-04-16 11:06:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本在运行,从我们的时间表MongoDB数据库更新excel电子表格。基本上,人们在我的webapp中输入他们的时间表,我通过Python脚本更新他们的excel电子表格。在

然而,当账单一个月后,我们会保护这张单子。有时,在受保护的工作表中,两周内的更新会交叉。在

我的问题是我当前的脚本擦除数据并在两周内重写它。但在受保护的工作表上,它将继续尝试写入,即使它受到保护,并且不会继续。它不会抛出错误,并一直尝试执行那行代码。在

我尝试实现超时,因为这行代码不会抛出错误,python也无法捕捉到它。但是,python不会经常检查while语句,因此它会看到当前时间最初小于超时值,但不会重新检查它,也不能,因为它被卡在代码行上。在

for j,user in enumerate(users):
    if user not in email_timesheet_dict:
        continue
    wb = xw.Book(email_timesheet_dict[user])
    app = xw.apps.active
    for sheet in sheets:
        time.sleep(1)                                 //What I've tried
        timeout = 30                                  //
        timeout_start = time.time()                   //
        print(time.time())                            //
        print(timeout_start)                          //
        print(timeout + timeout_start)                //
        while time.time() < timeout_start + timeout:  //What I've tried
            sht =wb.sheets[sheet]
            ...
            ...

这是它遇到的代码行:

^{pr2}$

我想知道是否有一种方法可以检查我正在编辑的工作表是否受保护,如果是,它将跳过它并转到下一个工作表。它是一个旧的excel文件(.xls),所以我需要它兼容。在


Tags: 代码in脚本fortimeemail错误timeout
1条回答
网友
1楼 · 发布于 2024-04-16 11:06:41

python doesn't check the while statement

因为应用程序挂在语句中的某个地方。通常会有一个对话框通知用户保护:

enter image description here

只要显示该对话框,Excel应用程序就没有响应。最好的办法可能是忽略受保护的床单。未经测试,但在评论中解释:

for sheet in sheets:
    sht = wb.sheets[sheet]
    alerts = wb.api.Application.DisplayAlerts  # get the current value of this property
    wb.api.Application.DisplayAlerts = False   # suppress the warning dialog which is freezing Excel Application
    try:
        sht.range(f'{col}{row}').value = None
    except:
        # if the range is not writeable, an error should be raised here.
        print(f'{sheet} is protected and can''t be written to...')
    finally:
        # return the application.DisplayAlerts to its previous value
        wb.api.Application.DisplayAlerts = alerts

相关问题 更多 >