簡體   English   中英

使用密碼加密的Python或LibreOffice Save xlsx文件

[英]Python or LibreOffice Save xlsx file encrypted with password

我正在嘗試保存使用密碼加密的Excel文件。 我嘗試按照https://help.libreoffice.org/Common/Protecting_Content_in上的指南進行操作-效果很好。 但是,這是在GUI中,但是我正在尋找在無頭模式下使用命令行界面的解決方案。

我看着那man libreoffice ,但是在那里找不到任何東西。

同樣,我查看了Python 3庫openpyxl的文檔,但是我也沒有發現任何有用的東西。

是否可以使用不需要任何用戶交互或X會話的命令行(或Python庫)在Ubuntu 14.04 / 16.04上保存使用密碼加密的Excel 2007+文件?

有使用JythonApache POI的解決方案。 如果您想從CPython / PyPy中使用它,則可以使用子進程模塊來調用外部Jython腳本。

  1. 我假設您已經安裝了Java JRE / JDK
  2. 使用Excel / Calc創建未加密的 xlsx文件,或使用xlsxwriteropenpyxl並將其保存為test1.xlsx
  3. 下載獨立的Jython
  4. 下載Apache POI
  5. 在獨立的Jython jar所在的目錄中提取Apache POI
  6. 將以下Jython腳本另存為crypto.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

哪里:

  • crypto.py-腳本名稱
  • test1.xlsx-輸入文件名
  • test1enc.xlsx-輸出文件名
  • 12345678-密碼

最終加密的 xslx應該在test1enc.xlsx中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM