python-3.xxlsxpassword-protection

How to password-protect an XLSX file in Python


I want to create an excel file with some data and password-protect the entire file, not just worksheets. I've looked around many places but I haven't found a way without paid libraries like spire.xls package. I couldn't install it for obscure reasons. I'm new in Python so those errors are beyond me. I found that here.


Solution

  • Alright, I got it. Thanks to the people in the comments. What I wanted was to create a file and copy it on some SMB server. The file is XLSX, needs a password to be opened and a sensitivity label.

    But as far as this question goes, to password-protect it, I created the file with xlswriter, created a plain handler, then opened an OOXMLFile with the previous handler, encrypted it (which means add a pwd to open it) then closed the original plain file:

    import xlsxwriter
    from msoffcrypto.format.ooxml import OOXMLFile
    
    wb = xlsxwriter.Workbook(INTERMEDIATE_EXCEL_FILE)
    ws = wb.add_worksheet()
    ws.write_row('A1', FIELD_NAMES, cell_format=None)
    r, c = 1, 0
    for row in records:
        ws.write_row(r, c, row)
        r = r + 1
    wb.close()
    plain = open(INTERMEDIATE_EXCEL_FILE, "rb")
    file = OOXMLFile(plain)
    with open(EXCEL_FILENAME, "wb") as f:
        file.encrypt(EXCEL_FILE_PASSWORD, f)
    plain.close()
    

    I also achieved it with xlwings but it was opening the file asking me for manual setup of the sensitivity label, which is why I ended up using openpyxl to add the label. I smbclient.shutil to copy the file to the shared drive.