Python or LibreOffice Save xlsx file encrypted with password

By : YnkDK

I am trying to save an Excel file encrypted with password. I have tried following the guide on - and works perfectly. However, this is in the GUI, but I am looking for a solution using the command line interface in headless mode.

I have looked at the man libreoffice, but I could not find anything in there.

Likewise I have looked at the documentation of the Python 3 library openpyxl, but I did not find anything useful there either.

Is it possible to save an Excel 2007+ file encrypted with a password on Ubuntu 14.04/16.04 using the command line (or Python library) that do not require any user interaction or X session?

By : YnkDK


There is solution using Jython and Apache POI. If you want like to use it from CPython/PyPy, you can use subprocess module to call external Jython script.

  1. I assume that you have Java JRE/JDK installed
  2. Create non-encrypted xlsx file with Excel/Calc or use xlsxwriter or openpyxl and save it as test1.xlsx
  3. Download standalone Jython
  4. Download Apache POI
  5. Extract Apache POI in same dir where is standalone Jython jar
  6. Save following Jython script as
import os
import sys
from import BufferedInputStream
from import FileInputStream
from import FileOutputStream
from import File
from import IOException
from org.apache.poi.poifs.crypt import EncryptionInfo, EncryptionMode
from org.apache.poi.poifs.crypt import CipherAlgorithm, HashAlgorithm
from org.apache.poi.poifs.crypt.agile import AgileEncryptionInfoBuilder
from org.apache.poi.openxml4j.opc import OPCPackage, PackageAccess
from org.apache.poi.poifs.filesystem import POIFSFileSystem
from import WorkbookFactory

def encrypt_xlsx(in_fname, out_fname, password):
    # read
    in_f = File(in_fname)
    in_wb = WorkbookFactory.create(in_f, password)
    in_fis = FileInputStream(in_fname)

    # encryption
    out_poi_fs = POIFSFileSystem()
    info = EncryptionInfo(EncryptionMode.agile)
    enc = info.getEncryptor()
    opc =, PackageAccess.READ_WRITE)
    out_os = enc.getDataStream(out_poi_fs)

    # write
    out_fos = FileOutputStream(out_fname)

if __name__ == '__main__':
    in_fname = sys.argv[1]
    out_fname = sys.argv[2]
    password = sys.argv[3]
    encrypt_xlsx(in_fname, out_fname, password)
  1. Call it from console:
java -cp "jython-standalone-2.7.0.jar:poi-3.15/lib/commons-codec-1.10.jar:poi-3.15/lib/commons-collections4-4.1.jar:poi-3.15/poi-3.15.jar:poi-3.15/poi-ooxml-3.15.jar:poi-3.15/poi-ooxml-schemas-3.15.jar:poi-3.15/ooxml-lib/curvesapi-1.04.jar:poi-3.15/ooxml-lib/xmlbeans-2.6.0.jar" org.python.util.jython -B test1.xlsx test1enc.xlsx 12345678


  • - name of script
  • test1.xlsx - input filename
  • test1enc.xlsx - output filename
  • 12345678 - password

Final encrypted xslx should be in test1enc.xlsx.

By : mtasic85

This video can help you solving your question :)
By: admin