58 lines
1.6 KiB
Python
Executable File
58 lines
1.6 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
import argparse
|
|
import os
|
|
import shutil
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
import msoffcrypto
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("source")
|
|
parser.add_argument("destination")
|
|
parser.add_argument("--password-file", required=True)
|
|
args = parser.parse_args()
|
|
|
|
source = Path(args.source)
|
|
destination = Path(args.destination)
|
|
password_file = Path(args.password_file)
|
|
if not source.is_file():
|
|
raise SystemExit(f"源文件不存在:{source}")
|
|
if not password_file.is_file():
|
|
raise SystemExit(f"密码文件不存在:{password_file}")
|
|
|
|
password = password_file.read_text(encoding="utf-8").strip()
|
|
if password == "":
|
|
raise SystemExit("供应商汇总表密码为空")
|
|
|
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
temp_fd, temp_name = tempfile.mkstemp(
|
|
prefix=destination.stem + ".",
|
|
suffix=".xlsx",
|
|
dir=destination.parent,
|
|
)
|
|
os.close(temp_fd)
|
|
temp_path = Path(temp_name)
|
|
|
|
try:
|
|
with source.open("rb") as source_handle:
|
|
office = msoffcrypto.OfficeFile(source_handle)
|
|
if office.is_encrypted():
|
|
office.load_key(password=password)
|
|
with temp_path.open("wb") as destination_handle:
|
|
office.decrypt(destination_handle)
|
|
else:
|
|
shutil.copyfile(source, temp_path)
|
|
os.replace(temp_path, destination)
|
|
finally:
|
|
temp_path.unlink(missing_ok=True)
|
|
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|