Recently our IT dept has applied a policy where we have to specify Sensitivity Label in Excel. This caused a disruption to my automated py codes to generate personalised excel files.
Besides using Excelwriter to write into the file, i also use win32com to password protect the individual files with random password. Whenever win32com opens the file, it is prompted to select the sensitivity label which it cannot get around and thus unable to proceed further.
Is there a way to programmatically default select 'confidential' as the sensitivity label?
following is briefly how i generate the files
while rc < idcount:
var_id= df['idnum'].iloc[rc]
var_password = df['password'].iloc[rc]
main_df = df[(df['idnum'] == var_id)]
wsname = 'testsheet'
staff_file = pd.ExcelWriter(dummyloc + 'Dummy.xlsx', engine='xlsxwriter')
main_df.to_excel(staff_file,wsname,startrow=4,index=False)
workbook = staff_file.book
workbook.set_vba_name('ThisWorkbook')
workbook.add_vba_project(dummyloc + './vbaProject.bin') #i added a macro for some internal controls.
staff_file.save()
staff_file.close()
excel = Dispatch('Excel.Application')
wb = excel.Workbooks.Open(dummyloc + 'Dummy.xlsx')
excel.Worksheets[wsname].Activate()
excel.ActiveSheet.Protect('ABCD',True ,True ,True ,False ,False , False , False , False , False , False , False ,False , True , True , False)
wb.SaveAs(Filename = dummyloc + 'Excel\\' + 'Dummy1',FileFormat= 52,Password=str(var_password))
wb.Close()
rc = rc+ 1
I have also found a suggested solution but somehow. It is supposed to execute a vba macro to inject the password. However, maybe i didnt code it correctly, it didn't change anything
def set_password(excel_file_path, pw):
from pathlib import Path
excel_file_path = Path(excel_file_path)
vbs_script = \
f"""' Save with password required upon opening
Set excel_object = CreateObject("Excel.Application")
Set workbook = excel_object.Workbooks.Open("{excel_file_path}")
excel_object.DisplayAlerts = False
excel_object.Visible = False
workbook.SaveAs "{excel_file_path}",, "{pw}"
excel_object.Application.Quit
"""
# write
vbs_script_path = excel_file_path.parent.joinpath("set_pw.vbs")
with open(vbs_script_path, "w") as file:
file.write(vbs_script)
#execute
subprocess.call(['cscript.exe', str(vbs_script_path)])
# remove
vbs_script_path.unlink()
return None