Search code examples
pythonpandasdataframepandas.excelwriter

How to password protect an excel file but allow read only in python?


I'm working on automatization in python and and I already created a read only excel file but is it possible to make it password protect to write?

I've made it this far

with pd.ExcelWriter("asd.xlsx", engine="xlsxwriter") as excel_writer:
    df4.to_excel(excel_writer, index=False, sheet_name="Sheet1")
    excel_writer.book.read_only_recommended()

Solution

  • You may accomplish the task using Aspose.Cells for Python via Java easily. See the following sample code that will make the Excel file write-protected with password for your reference. e.g. Sample code:

    import jpype
    import asposecells
    jpype.startJVM()
    from asposecells.api import Workbook
    
    # Load the MS Excel file.
    workbook = Workbook("asd.xlsx")
        
    
    # Write protect workbook with password.
    workbook.getSettings().getWriteProtection().setPassword("1234");
    
    # Specify author while write protecting workbook.
    workbook.getSettings().getWriteProtection().setAuthor("testauthor1");
    
    
    # Save the write-protected Excel file.
    workbook.save("out_protected-asd.xlsx")
    

    When you open the output file into MS Excel manually, you will be prompted to specify the write-protected password. If you want to change/update the contents in the file, you will give the correct password. Otherwise, you can open the file as "Read only" for read-only purpose.

    You may also post your queries or comments in the dedicated forums.

    PS. I am working as Support developer/ Evangelist at Aspose.