如何使用Python以编程方式设置Excel敏感度标签?

问题描述 投票:0回答:2

最近我们的 IT 部门应用了一项政策,我们必须在 Excel 中指定敏感度标签。 这导致我的自动 py 代码生成个性化 Excel 文件的中断。

除了使用Excelwriter写入文件外,我还使用win32com使用随机密码来保护各个文件。每当 win32com 打开文件时,都会提示选择它无法绕过的敏感度标签,从而无法继续进行。

有没有办法以编程方式默认选择“机密”作为敏感度标签?

以下是我如何生成文件的简要说明

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

我还找到了一个建议的解决方案,但不知何故。 它应该执行一个 vba 宏来注入密码。然而,也许我没有正确编码,它没有改变任何东西

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 
python excel vba win32com pandas.excelwriter
2个回答
3
投票

刚刚在我的工作场所更新 Excel 365 时遇到了类似的问题。简而言之,我通过上网管理的是一个快速的VBA函数,它从已经标记的文件中获取敏感度标签,然后将其分配给我需要的所有文件。

请原谅我将 VBA 代码放入 Python 问题中,但由于您使用的是 win32com,因此改编应该非常简单。

这是我写的函数:

Sub put_label()
    'Puts sensitivity labels copied from active workbook to a list of files.
    Dim ex_lab  'To store the label object
    Dim fs, f, archivos, curarch
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(Range("C2").Value2)
    Set archivos = f.Files  'List of files to be labelled
    
    'This line gets the label object from the already labelled file.
    Set ex_lab = ActiveWorkbook.SensitivityLabel.GetLabel()
    
    'The label is applied to all the files.
    For Each curarch In archivos
        Workbooks.Open curarch.path, False
        'ActiveWorkbook is now the just opened workbook
        ActiveWorkbook.SensitivityLabel.SetLabel ex_lab, ex_lab
        ActiveWorkbook.Save
        ActiveWorkbook.Close False
    Next
   
   MsgBox "Done"
    
End Sub

因此,根据您所拥有的,您可以使用 excel_object 并直接引用工作簿对象等,因为这些方法通常看起来与 VBA 中的相同。只不过要注意的是,在Python中使用时,所有的函数都用()来表示。例如,VBA 的:

ActiveWorkbook.Close False

应采用 Python 代码,如下所示:

excel_object.ActiveWorkbook.Close(False)

此外,Set 语句是 VBA 声明对象而不是内置变量的方式;在 Python 中不需要。

有时会存在一些区分大小写的问题,但我想您已经有通过 COM 对象从 Python 使用 VBA 的经验了。

希望这有帮助,整个早上都在担心这个问题:)


0
投票

我运行了许多软件包来解决敏感度标签问题,由于能够使用 set_custom_property,我选择了 xlsx writer。您不能使用 xlsx writer 设置标签和 pd.excelwriter 粘贴数据框。我通过以下代码解决了敏感度标签问题,该代码使用数据框保存文件 1 excel,但没有标签,并创建带有标签的文件 2 excel。然后,它将带有正确标签的工作表从文件 1 复制到文件 2。

import pandas as pd
import xlsxwriter
import os
from win32com.client import Dispatch

# get folder path of the current folder
cwd = os.getcwd()
path1 = fr'{cwd}\newCopy.xlsx'
path2 = fr'{cwd}\output.xlsx'

def copy_sheet(path1, path2, num):
    xl = Dispatch("Excel.Application")
    wb1 = xl.Workbooks.Open(Filename=path1)
    wb2 = xl.Workbooks.Open(Filename=path2)
    ws1 = wb1.Worksheets(num)
    ws1.Copy(Before=wb2.Worksheets(num))
    wb1.Close(SaveChanges=False)
    wb2.Close(SaveChanges=True)
    xl.Quit()

# Create a Pandas DataFrame (example data)
data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 35],
        'City': ['New York', 'Los Angeles', 'Chicago']}

df = pd.DataFrame(data)
writer = pd.ExcelWriter(path1)
df.to_excel(writer, engine='xlsxwriter', sheet_name='CIM')
df.to_excel(writer, engine='xlsxwriter', sheet_name='CDC')
writer.close()

with xlsxwriter.Workbook(path2) as writer:
    '''You need to get the id's '''
    company_guid = "9f367a1c-3d38-4c2c-9d10-a1726879ca5b"
    site_id = "9f367a1c-3d38-4c2c-9d10-a1726879ca5b"
    action_id = "9f367a1c-3d38-4c2c-9d10-a1726879ca5b"
    writer.set_custom_property(f"MSIP_Label_{company_guid}_ActionId", action_id, "text")
    writer.set_custom_property(f"MSIP_Label_{company_guid}_Enabled", "true", "text")
    writer.set_custom_property(f"MSIP_Label_{company_guid}_Method", "Privileged", "text")
    writer.set_custom_property(f"MSIP_Label_{company_guid}_SiteId", site_id, "text")


copy_sheet(path1, path2, 1) # Copy sheet 1
copy_sheet(path1, path2, 2) # Copy sheet 2
if os.path.exists(path1):
  os.remove(path1)
else:
  print("The file does not exist")
© www.soinside.com 2019 - 2024. All rights reserved.