Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting sensitivity label for excel file using python [duplicate]

I was trying to load a dataframe into an excel template using openpyxl and save it at the highest sensitivity setting. The template has 5 levels of sensitivity set by the Microsoft admins, with the highest level being "Highly Protected". Pic for reference

The template is saved as "Highly Protected" but once the data is loaded in, the new file reverts to "General Business" label.

# Load template file
template_path = filepath.xlsx
tmpwb = openpyxl.load_workbook(template_path)

#   select sheet
sheet = tmpwb['Data']

# update columns names
for i, col in enumerate(df.columns):
    sheet.cell(row=2, column=i+1).value = col

# update main data table
for i, col in enumerate(df.columns):
    for j, df_value in enumeratedf[col]):
        sheet.cell(row=j+3, column=i+1).value = df_value

file_path = savepath.xlsx

# save workbook
tmpwb.save(file_path)

Is there a way I can control the sensitivity settings using python? Thanks for any tips.

like image 843
Allaniano Avatar asked Dec 31 '25 17:12

Allaniano


1 Answers

The sensitivity label is Office365 Parameter which can be modified with xlwings and the pywin32 API.

The only thing you need to do first is to find out the individual ID's of the classifications.

import xlwings as xw
wb = xw.Book('test.xlsx') #A workbook with a set activity label

labelinfo = wb.api.SensitivityLabel.GetLabel()
print(labelinfo.LabelId)
>>> 123123123-123123123-ajskldfj123  (as an example ID, this will look different for each LabelName)

This will give you the ID of the Sensitivity Label, which you can then pass to the modified xls at the end. This will look different for each LabelName. So you will first (one time action) need to find out your Company's ID for these Sensitivity Labels Then you set the Label, like below:

wb = xw.Book('test.xlsx')
labelinfo = wb.api.SensitivityLabel.CreateLabelInfo()
labelinfo.AssignmentMethod = 2
labelinfo.Justification = 'init'
labelinfo.LabelId = 'YOUR-ID-GOES-HERE'
wb.api.SensitivityLabel.SetLabel(labelinfo, labelinfo)

This should set your Sensitivity label correctly.

You can learn more about this here

like image 88
Akula1 Avatar answered Jan 02 '26 06:01

Akula1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!