VB.Net Excel Automation how to handle Sensitivity Labels

Viewed 1082

When I'm creating an Excel file for a user in VB.Net, I am getting an error ("You can't perform this action when the file is read-only") when I try to save the file and it seems to be because a Sensitivity Label hasn't been chosen. I haven't been able to find any documentation on handling Sensitivity Labels when performing Excel Automation so I was wondering if anyone has run into this issue or knows of any documentation? Is there a way to set the Sensitivity programmatically?

2 Answers

I created a template file (stored in database and brought down to the local machine) that I set the Sensitivity on and then populated that instead of creating the Excel file through the Automation process.

The syntax is Python because that is what I am using, but since win32com.client is just a COM wrapper, this should (with the proper VB syntax) work for you.

You will need the following data, which you can extract from a file where you previously manually set the sensitivity label to your desired value:

existing_sl = existing_doc.SensitivityLabel.GetLabel()
label_id = existing_sl.LabelId
label_name = existing_sl.LabelName

label_id will be a UUID and label_name a string. Then, with this data, you can create and set a new sensitivity label as follows.

label_id = <the label ID you retrieved from the existing file>
label_name = <the label name your retrieved from the existing file>

new_sl = another_doc.SensitivityLabel.CreateLabelInfo()
new_sl.ActionId = str(uuid.uuid1())
new_sl.AssignmentMethod = 1
new_sl.ContentBits = 0
new_sl.IsEnabled = True
new_sl.Justification = ''
ew_sl.LabelId = label_id 
new_sl.LabelName = label_name 
new_sl.SetDate = '2022-08-15T07:02:00Z'
new_sl.SiteId = str(uuid.uuid1())
another_doc.SensitivityLabel.SetLabel(new_sl, new_sl)

The uuid.uuid1() function is just the Phython function to create a random UUID. You could also use something else or a fixed one. I did not text it thoroughly, but it works with the random one at least. As far as I could find out, the SiteId variable need not be the same as in the original label. As for SetDate, I was just lazy and set it to some value. Being completely proper, you could use now or an equivalent function to generate a (properly-formatted) datetime string.

AssignmentMethod uses the MsoAssignmentMethod enumeration. 1 is just "The label was manually selected".

The Python code requires the following imports

import win32com.client
import uuid

You can find some references here and here.

If you manage to get it to work in VB, feel free to post the result :)

Related