如何显示和更改Word文档(桌面)的SentivityLabel



我想知道我当前Word文件的敏感度标签,用新值更改它并保存我的文件

我首先打开一个Word文件

# Opening a MS Word file in pywin32
from win32com.client import Dispatch
myWord = Dispatch('Word.Application')
myWord.Visible = 1
myWord.Documents.Open("C:/./TEMP.docx")  # open file
# SetLabel and GetLabel
print(myWord.ActiveDocument.SensitivityLabel)
print(myWord.ActiveDocument.SensitivityLabel.SetLabel)
print(myWord.ActiveDocument.SensitivityLabel.GetLabel())
# Create label info
myLabelInfoNew = myWord.ActiveDocument.SensitivityLabel.CreateLabelInfo()
# Close Word Application
myWord.ActiveDocument.SaveAs("C:/./TEMP2.docx")
myWord.Quit()

我该怎么修?

感谢您的帮助

我无法修复它,但我可以建议一个替代方案。

使用python子流程模块调用powershell,因为Microsoft提供了powershell工具来读取和应用敏感度标签。这些工具是Get-AIPFileStatusSet-AIPFileLabel。我建议在回到python之前,先在powershell中与它们一起玩,以便更好地理解它。

我刚刚用Python发布了这个解决方案的要点。

这是我读取标签的功能:

import json
import subprocess
def read_label(
filepath,
full_result=False,
powershell=r'C:WINDOWSsystem32WindowsPowerShellv1.0powershell.exe',
stdout_encoding='iso8859-15',
):
# The command to call in powershell. It includes the powershell tool
# 'ConvertTo-Json' to make it easier to process the results in Python,
# specially when the file path is too long, which may break lines.
command = f"Get-AIPFileStatus -path '{filepath}' | ConvertTo-Json"
# Executing it
result = subprocess.Popen([powershell, command], stdout=subprocess.PIPE)
result_lines = result.stdout.readlines()
# Processing the results and saving to a dictionary
clean_lines = [
line.decode(stdout_encoding).rstrip('rn') for line in result_lines
]
json_string = 'n'.join(clean_lines)
result_dict = json.loads(json_string)
# If selected, return the full results dictionary
if full_result:
return result_dict
# If not returns only the label_id of interest to apply to other document
# Per Microsoft documentation if a sensitivity label has both a
# 'MainLabelId' and a 'SubLabelId', only the 'SubLabelId' should be used
# with 'Set-AIPFileLabel' tool to to set the label in a new document.
label_id = (
result_dict['SubLabelId']
if result_dict['SubLabelId']
else result_dict['MainLabelId']
)
return label_id

这里是应用它的函数:

import subprocess
import time
def apply_label(
filepath,
label_id,
powershell=r'C:WINDOWSsystem32WindowsPowerShellv1.0powershell.exe',
stdout_encoding='iso8859-15',
):
start = time.time()
# The command to call in powershell
command = f"(Set-AIPFileLabel -path '{filepath}' -LabelId '{label_id}').Status.ToString()"
# Executing it
result = subprocess.Popen([powershell, command], stdout=subprocess.PIPE)
result_message = (
result.stdout.readline().decode(stdout_encoding).rstrip('rn')
)
# If the command is not successful, raises an exception and display the message
# from 'Set-AIPFileLabel' tool
if result_message != 'Success':
raise Exception(result_message)
end = time.time()
return end - start

这是我用来将敏感度应用于.xlsx文档的代码。为公司使用的每种敏感度类型创建一个.docx文件。在每个敏感度类型的文档上运行第一个函数,您必须获得每个类型的公司敏感度ID。然后使用适当的ID更新第二个函数中的字典。为了处理.docx文件,您需要更改以下代码中的一些内容。有关更改,请参阅以下项目。

  1. 从'Excel.Application'到'Document.Application'
  2. .工作簿.打开文档.打开
  3. .ActiveWorkbook到.ActivateDocument

下面的docx 更新

from win32com.client import Dispatch
def get_lable(in_xlsx):
"""
:param in_xlsx: Input file to attach sensitivity label
"""
myxlsx = Dispatch('Excel.Application')
myxlsx.Visible = 1
myxlsx.Workbooks.Open(in_xlsx)
# Get Label
label_id = myxlsx.ActiveWorkbook.SensitivityLabel.GetLabel()
print(str(label_id))
myxlsx.Application.Quit()
return str(label_id)
def xlsx_sensitivity_label(in_xlsx, label='Internal'):
"""
Update XLSX file with sensitivity label
https://pythoninoffice.com/python-set-sensitivity-label-in-excel/
:param in_xlsx: path of input .xlsx file to attach sensitivity label
:param label: Accepted Labels: Public, Internal, Confidential, Restricted
:return: Adds Microsoft Sensitivity label to spreadsheet
"""
di_sensitivity = {'Public': 'xxxx-xxx-xxxxxxx-xxxx-xxx-xxx',
'Confidential': 'xxxx-xxx-xxxxxxx-xxxx-xxx-xxx',
'Internal': 'xxxx-xxx-xxxxxxx-xxxx-xxx-xxx',
'Restricted': 'xxxx-xxx-xxxxxxx-xxxx-xxx-xxx'}
label_id = di_sensitivity[label]
myxlsx = Dispatch('Excel.Application')
myxlsx.Visible = 1
myxlsx.Workbooks.Open(in_xlsx)
# Set Label
label_info = myxlsx.ActiveWorkbook.SensitivityLabel.CreateLabelInfo()
label_info.AssignmentMethod = 2
label_info.LabelId = label_id
label_info.LabelName = label
print(label_info.LabelName)
myxlsx.ActiveWorkbook.SensitivityLabel.SetLabel(label_info,label_info)
myxlsx.ActiveWorkbook.Save()
myxlsx.Application.Quit()

最新更新