Search code examples
pythonpandasxlsxwriter

Is it possible to save .xlsx as read-only using pandas?


It feels like there should be a way to save a .xlsx file as read-only using pandas' to_excel function or the XLSXwriter module.

I have looked at both documentations without luck.

to_excel: https://pandas.pydata.org/pandasdocs/stable/generated/pandas.DataFrame.to_excel.html

XLSXwriter: http://xlsxwriter.readthedocs.io/workbook.html

Is there another way to achieve this within pandas?


Solution

  • Here is one way to do it with Pandas when using xlsxwriter as the engine:

    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("pandas_read_only.xlsx", engine="xlsxwriter")
    
    # Convert the dataframe to an XlsxWriter Excel object.
    df.to_excel(writer, sheet_name="Sheet1")
    
    # Set the Excel output file as "Read-only Recommended".
    writer.book.read_only_recommended()
    
    # Close the Pandas Excel writer and output the Excel file.
    writer.close()
    

    Output when opening file:

    enter image description here