Last active
November 8, 2023 12:18
-
-
Save arrowinaknee/46c88811abb46fae771cbbda5e12008b to your computer and use it in GitHub Desktop.
Снимает защиту от редактирования с файлов MS Word (.docx) и MS Excel (.xlsx)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import shutil | |
import tempfile | |
import re | |
import sys | |
import tkinter as tk | |
from tkinter import filedialog | |
from tkinter import messagebox | |
def unlock(source_file): | |
file_path = os.path.split(source_file)[0] + "\\" | |
file_name = os.path.splitext(os.path.split(source_file)[1])[0] | |
file_extension = os.path.splitext(source_file)[1] | |
temp_dir = tempfile.gettempdir() + "/excel_unlocker" | |
target_file = file_path + file_name + "_unlocked" + file_extension | |
if not os.path.exists(temp_dir): | |
os.mkdir(temp_dir) | |
if file_extension != ".xlsx" and file_extension != ".docx": | |
messagebox.showerror("Неподдерживаемый тип", "Файлы формата " + file_extension + " не поддерживаются\nДанный скрипт поддерживает снятие блокировки только с файлов MS Word (.docx) и MS Excel (.xlsx)") | |
exit(0) | |
# Unpack the file to temporary location | |
unpack_dir = temp_dir + "/unpacked" | |
if os.path.exists(unpack_dir): shutil.rmtree(unpack_dir) | |
shutil.unpack_archive(source_file, unpack_dir, "zip") | |
# Remove protection from files | |
if file_extension == ".xlsx": | |
# excel files | |
folder = unpack_dir + "/xl/worksheets" | |
# remove protection from individual sheets | |
for sheetfile in os.listdir(folder): | |
if sheetfile.endswith(".xml"): | |
sheetfile_object = open(folder + "/" + sheetfile, "r") | |
sheet_xml = sheetfile_object.read() | |
sheetfile_object.close() | |
result_file = open(folder + "/" + sheetfile, "w") | |
result_file.write(re.sub("<sheetProtection[^>]*/>", "", sheet_xml)) | |
result_file.close() | |
# remove protection from the workbook | |
workbook_object = open(unpack_dir + "/xl/workbook.xml", "r") | |
workbook_xml = workbook_object.read() | |
workbook_object.close() | |
result_file = open(unpack_dir + "/xl/workbook.xml", "w") | |
result_file.write(re.sub("<workbookProtection[^>]*/>", "", workbook_xml)) | |
result_file.close() | |
elif file_extension == ".docx": | |
# word file, only settings.xml affected | |
settings_object = open(unpack_dir + "/word/settings.xml", "r") | |
settings_xml = settings_object.read() | |
settings_object.close() | |
result_file = open(unpack_dir + "/word/settings.xml", "w") | |
result_file.write(re.sub("<w:documentProtection[^>]*/>", "", settings_xml)) | |
result_file.close() | |
# Pack the file back again | |
archive = shutil.make_archive(temp_dir + "/result", "zip", unpack_dir) | |
if os.path.exists(target_file): | |
os.remove(target_file) | |
os.rename(archive, target_file) | |
messagebox.showinfo("Операция завершена", "Файл \"" + os.path.split(target_file)[1] + "\" в \"" + file_path + "\" готов к использованию") | |
root = tk.Tk() | |
root.withdraw() | |
source_file = '' | |
if len(sys.argv) <= 1: | |
source_file = filedialog.askopenfilename() | |
# file dialog closed | |
if source_file == "": | |
exit(0) | |
else: | |
source_file = sys.argv[1] | |
try: | |
unlock(os.path.abspath(source_file.replace("'", "").replace("\"", ""))) | |
except SystemExit: | |
pass | |
except: | |
messagebox.showerror("Непредвиденная ошибка", sys.exc_info()[0]) |
Для обеспечения кросс-платформенности в отношении путей к файлам рекомендую использовать
pathlib
Рассматриваю либо такой вариант, либо просто функции os.path
, но в данный момент нет времени на обновление скрипта
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Для обеспечения кросс-платформенности в отношении путей к файлам рекомендую использовать
pathlib