Search code examples
pythonexcelediting

How make a protect from editing excel file?


I create a excel file from a dataframe:

#writer = pd.ExcelWriter('test_1.xlsx', engine='xlsxwriter')    
#uniq_pros.to_excel(writer, sheet_name='Sheet1')
#writer.save()

how can make it protect from editing this excell file? i want be only for view from users...


Solution

  • You can do that as follows using the XlsxWriter worksheet protect() method:

    import pandas as pd
    
    
    # Create a Pandas dataframe from some data.
    df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
    
    # Create a Pandas Excel writer using XlsxWriter as the engine.
    writer = pd.ExcelWriter('test_1.xlsx', engine='xlsxwriter')
    
    # Convert the dataframe to an XlsxWriter Excel object.
    df.to_excel(writer, sheet_name='Sheet1')
    
    # Get the xlsxwriter workbook and worksheet objects.
    workbook  = writer.book
    worksheet = writer.sheets['Sheet1']
    
    # Set protection for the worksheet.
    worksheet.protect()
    
    # Close the Pandas Excel writer and output the Excel file.
    writer.save()
    
    

    Output:

    enter image description here

    You can also add a password if required.