[Python] Setting Sensitivity Label for Excel Using Win32Com (Python)

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on creating some scripts for our team to use with some new sensitivity labels that were recently implemented. I ultimately need a script that will get the current classification, and a script that will set the classification.

    I have the script that returns the GUID of the sensitivity label, and that functions fine. I'm having issues when I'm trying to run SensitivityLabel.SetLabel though.

    Here is what I've been trying to use to set the sensitivity label (unsuccessfully).

    import win32com.client as win32
    import os

    file = os.path.join(os.getcwd() + book)

    excel = win32.gencache.EnsureDispatch("Excel.Application")

    excel.DisplayAlerts = False
    excel.Visible = False

    try:
    workbook = excel.Workbooks.Open(file)
    except Exception as e:
    print(e)
    workbook = None

    assert workbook != None

    workbook.Activate

    label = workbook.SensitivityLabel.CreateLabelInfo()
    label.LabelId = 'guid here, verified by getLabel function'
    workbook.SensitivityLabel.SetLabel(label,label)

    excel.ActiveWorkbook.Save()
    excel.ActiveWorkbook.Close(True)
    excel.Application.Quit()

    workbook = None
    excel = None


    I thought that this would be sufficient, as its what I've seen others using and it seems to work there - but I'm getting a com_error.

    ' --------------------------------------------------------------------------- com_error Traceback (most recent call last) Cell In[19], line 34 32 label = workbook.SensitivityLabel.CreateLabelInfo() 33 label.LabelId = '6d47f64f-b290-43a1-b909-b6568bad646' ---> 34 workbook.SensitivityLabel.SetLabel(label,label) 36 excel.ActiveWorkbook.Save() 37 excel.ActiveWorkbook.Close(True)

    File <COMObject SensitivityLabel>:2, in SetLabel(self, LabelInfo, Context)

    com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147467259), None)


    '

    Continue reading...

Compartilhe esta Página