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

How to detect protected worksheet in excel workbook using Python xlwings?

我有一个脚本 运行 更新 excel 从我们的时间 sheet MongoDB 数据库传播 sheets。本质上,人们在我的网络应用程序中输入他们的时间 sheets,我通过 Python 脚本更新他们的 excel spreadsheets。

但是,当一个月的账单完成后,我们会保护它 sheet。有时,在受保护的 sheet.

中的两周内会有交叉更新。

我的问题是我当前的脚本基本上在那两周的时间段内擦除数据并重写数据。但是在受保护的 sheet 上,它会继续尝试写入它,即使它受保护并且不会继续。它不会抛出错误,并继续尝试执行该行代码。

我尝试实施超时,因为该行不会引发错误并且 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]
            ...
            ...

这是卡住的代码行:

sht.range(f"{col}{row}").value = None

我想知道是否有办法检查我正在编辑的 sheet 是否受到保护,如果受到保护,它会跳过它并转到下一个 sheet。这是一个较旧的 excel 文件 (.xls),所以我需要它兼容。

python doesn't check the while statement

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

只要显示该对话框,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