Search code examples
pythonexceldataframepysparkencryption

How can i create a excel xlsx file with required password when open in Linux using Python


I have a dataframe. I need to write dataframe to excel file with password required when open it. On Linux environment. How can i do that?

I try some packages like msoffcrypto, but it just can decrypt. encrypt feature is EXPERIMENT, cann't use now. pywin32 and xlings just available on Win or Mac, so cann't use too. I stucked. Help me


Solution

  • The encryption capabilities of msoffcrypto are indeed labeled as experimental, but as of the latest version (v.5.3.1), they are already usable.

    It is a third-party tool, however, so no guarantees can be provided regarding its use.

    CLI:

    msoffcrypto-tool -e -p Passw0rd plain.xlsx encrypted.xlsx
    

    Python code:

    import msoffcrypto
    
    file_path = "encrypted.xlsx"
    password = "Passw0rd"
    decrypted_file_path = "decrypted.xlsx"
    
    with open(file_path, "rb") as encrypted:
        file = msoffcrypto.OfficeFile(encrypted)
        file.load_key(password=password)  # Load the encryption key (password)
        with open(decrypted_file_path, "wb") as decrypted:
            file.decrypt(decrypted)
    

    Disclaimer: I am the author of msoffcrypto.