在没有 Windows 专用工具的情况下向现有 xlsx 添加密码(无人值守)

Add a password (unattended) to existing xlsx without Windows exclusive tools

我正在使用 Openpyxl 生成 xlsx 文件。我想使用我在同一脚本中作为变量的密码来保护 workbook 本身。这可以使用“文件”>“密码”手动设置...并在 Excel 本身中设置 "Password to open"。

Openpyxl 似乎仅通过 ws.protection.set_password("mypassword") 提供基于 sheet 的编辑保护(其中 ws 是开放作品 sheet)

我似乎找不到确切的例子,但我在某处读到 xlsx 文件基本上是 zip 存档,虽然当我 运行 命令 unzip -t 和 [=15] 时它看起来是真的=] 似乎使用 7zzipcloak 等实用程序添加密码会在文件放回原处时完全破坏文件。

 % 7z x ../sample.xlsx .

7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21
p7zip Version 16.02 (locale=utf8,Utf16=on,HugeFiles=on,64 bits,4 CPUs x64)

Scanning the drive for archives:
1 file, 98370 bytes (97 KiB)

Extracting archive: ../sample.xlsx
--
Path = ../sample.xlsx
Type = zip
Physical Size = 98370


No files to process
Everything is Ok

Files: 0
Size:       0
Compressed: 98370
 % 7z a -pmypassword sample.xlsx

7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21
p7zip Version 16.02 (locale=utf8,Utf16=on,HugeFiles=on,64 bits,4 CPUs x64)

Scanning the drive:
1 file, 6148 bytes (7 KiB)

Creating archive: sample.xlsx

Items to compress: 1


Files read from disk: 1
Archive size: 367 bytes (1 KiB)
Everything is Ok
 % open sample.xlsx

用Excel打开时:

Excel cannot open the file 'sample.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.

请注意,无论我使用哪种类型 7z,结果都是相同的,zipcloak 也一样。

到目前为止,我已经使用 Bash 和 Python 查看了我的选项,它看起来非常糟糕。但我对任何事情都持开放态度。我在 运行 OS X 和 Debian 上执行此操作的机器。

您所要求的目前在任何 Python 软件包中均不可用。你现在可能做的最好的事情是安装一个用其他语言实现的包,然后从 Python 调用 that 包(使用 os.system() or the subprocess 模块或其他东西那些线)。

我知道的两个是

secure-spreadsheet 基本上是 xlsx-populate.

的命令行包装器

您似乎希望能够在不安装 Excel 的情况下执行此操作,但为了完整起见,我会提到如果您确实安装了 Excel,那么还有另一种方法可以执行此操作是自动化 Excel 本身,这可以在 Python 中使用 Mac 上的 xlwings, or the underlying packages that it depends upon: pywin32 on Windows or appscript 来完成。