Python或LibreOffice保存用密码encryption的xlsx文件

我正在尝试保存用密码encryption的Excel文件。 我已经尝试遵循https://help.libreoffice.org/Common/Protecting_Content_in上的指导 – 并且完美地工作。 但是,这是在GUI中,但我正在寻找一种解决scheme,在无头模式下使用命令行界面。

我看过那个man libreoffice ,但是在那找不到任何东西。

同样我也看过Python 3库openpyxl的文档,但是我没有发现任何有用的东西。

是否可以使用不需要任何用户交互或X会话的命令行(或Python库)在Ubuntu 14.04 / 16.04上保存使用密码encryption的Excel 2007+文件?

有使用Jython和Apache POI的解决scheme。 如果你想从CPython / PyPy中使用它,你可以使用subprocess模块来调用外部的Jython脚本。

  1. 我假设你已经安装了Java JRE / JDK
  2. 使用Excel / Calc创build未encryption的 xlsx文件,或使用xlsxwriter或openpyxl并将其另存为test1.xlsx
  3. 下载独立的Jython
  4. 下载Apache POI
  5. 在独立的Jython jar的相同目录中提取Apache POI
  6. 将以下Jython脚本另存为encrypt.py
 import os import sys from java.io import BufferedInputStream from java.io import FileInputStream from java.io import FileOutputStream from java.io import File from java.io 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 org.apache.poi.ss.usermodel 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) in_wb.close() # encryption out_poi_fs = POIFSFileSystem() info = EncryptionInfo(EncryptionMode.agile) enc = info.getEncryptor() enc.confirmPassword(password) opc = OPCPackage.open(in_f, PackageAccess.READ_WRITE) out_os = enc.getDataStream(out_poi_fs) opc.save(out_os) opc.close() # write out_fos = FileOutputStream(out_fname) out_poi_fs.writeFilesystem(out_fos) out_fos.close() 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. 从控制台调用它:
 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 encrypt.py test1.xlsx test1enc.xlsx 12345678 

哪里:

  • encrypt.py – 脚本的名称
  • test1.xlsx – input文件名
  • test1enc.xlsx – 输出文件名
  • 12345678 – 密码

最终encryption的 xslx应该在test1enc.xlsx中