我正在使用 Openpyxl 生成 xlsx 文件。我想使用我在同一脚本中作为变量的密码来保护工作簿本身。可以使用"file">“密码”手动设置,并在 Excel 本身中设置“打开密码”。
Openpyxl 似乎仅通过 ws.protection.set_password("mypassword")
提供基于工作表的编辑保护(其中 ws
是一个打开的工作表)
我似乎找不到确切的示例,但我在某处读到 xlsx 文件基本上是 zip 存档,虽然当我运行 unzip -t
和 7z 等命令时,这似乎是正确的x
似乎使用 7z
或 zipcloak
等实用程序添加密码会在文件重新组合在一起时完全破坏文件。
% 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 调用那个包(使用 os.system()
或 subprocess
模块或类似的东西)。
我所知道的两个是
secure-spreadsheet
基本上是 xlsx-populate
的命令行包装器.
您似乎希望能够在不安装 Excel 的情况下执行此操作,但为了完整起见,我会提到,如果您确实安装了 Excel,那么另一种方法就是使 Excel 本身自动化,这可以完成在Python中使用xlwings ,或其依赖的底层包:pywin32在 Windows 上或 appscript在 Mac 上。
关于python - 无需Windows专用工具即可向现有xlsx添加密码(无人值守),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50245208/