我想知道我当前 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()
我该如何解决?
谢谢你的帮助
这是我用来对 .xlsx 文档应用敏感度的代码。为贵公司使用的每种敏感度类型创建一个 .docx 文件。在每个敏感类型文档上运行第一个函数,您必须获取公司每种类型的敏感 ID。然后,您使用适当的 ID 在第二个函数中更新字典。要使其在 .docx 文件上运行,您需要更改以下代码中的一些内容。请查看以下项目以进行更改。
下面的 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()
我无法修复它,但我可以提出替代方案。
使用python subprocess 模块调用powershell,因为微软提供了powershell工具来读取和应用敏感度标签。 这些工具是
Get-AIPFileStatus
和Set-AIPFileLabel
。我建议在回到 python 之前在 powershell 中玩它们以更好地理解它。
我刚刚用 Python 发布了这个解决方案的gist。
这是我阅读标签的功能:
import json
import subprocess
def read_label(
filepath,
full_result=False,
powershell=r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.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('\r\n') 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:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.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('\r\n')
)
# 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