如何防止编辑 excel 文件?

How make a protect from editing excel file?

我从数据帧创建了一个 excel 文件:

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

如何防止编辑此 excell 文件? 我想只供用户查看...

“单击主 Excel 功能区上的“审阅”选项卡。单击“保护 Sheet。”输入您以后要用来解锁 sheet 的密码。重新输入您输入的密码以确认您记得它,然后单击“确定”。 (在 Excel 本身) 在 python 中,您可能可以对其进行加密: 以下是一些有用的资源:

https://blog.aspose.com/2021/06/01/encrypt-and-decrypt-excel-files-in-python/

Password Protecting Excel file using Python

https://www.easyxls.com/manual/tutorials/python/protect-excel-sheet-cells.html

您可以使用 XlsxWriter 工作表 protect() 方法,如下所示:

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()

输出:

如果需要,您还可以添加密码。