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

I am creating an xlsx file using Openpyxl. And I would like to protect the book myself using a password that I have as a variable in the same script. This can be set manually using "File"> "Passwords" .. and set "Password to open" in Excel itself.

Openpyxl only seems to offer sheet-based protection with ws.protection.set_password("mypassword")

(where ws

is the open sheet)

I can't find exact examples, but somewhere I read that the xlsx files were mostly zip archives, and although it seemed that when I ran commands like unzip -t

and 7z x

it seems that adding a password using utilities for example, 7z

or zipcloak

completely breaks the file when it comes back together.

 % 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

      

When opened with Excel:

Excel cannot open the sample.xlsx file because the file format or file extension is not valid. Make sure the file is not damaged and that the file extension matches the file format.

Note that the result is the same no matter what type I use with 7z

as well as with zipcloak

.

So far I've looked at my options with Bash and Python and it seems pretty heavy. But I'm pretty much open to anything .. The machines I do this run OS X and Debian.

+1


source to share


1 answer


What you are asking for is not currently available in any Python package. For now, your best bet is to install a package implemented in some other language and invoke that package from Python (using os.system()

either subprocess

or or something along those lines).

Two of them that I know



secure-spreadsheet

is basically a command line shell for xlsx-populate

.

It looks like you want to do this without installing Excel, but for completeness, I mentioned that if you have Excel installed then another way to do it is to automate Excel itself, which can be done in Python using xlwings or the base packages it depends on: pywin32 on Windows or appscript on Mac.

+1


source







All Articles