Python xlsx 单元格保护(锁定)
我需要把一个列表导出到Excel里,并且想要保护一些单元格或列,让它们只能被读取,不能被修改。
我现在用的是openpyxl这个Python模块来写xlsx文件,但我觉得只有xlwt这个模块有单元格保护的功能。而且xlwt好像不支持xlsx格式。
有没有人找到什么解决办法?
1 个回答
4
Python的一个模块叫做 XlsxWriter,它可以用来创建XLSX格式的文件,并且可以给工作表中的单元格添加保护(还有其他功能)。
from xlsxwriter.workbook import Workbook
workbook = Workbook('protection.xlsx')
worksheet = workbook.add_worksheet()
# Create a cell format with protection properties.
unlocked = workbook.add_format({'locked': False})
# Format the columns to make the text clearer.
worksheet.set_column('A:A', 40)
# Turn worksheet protection on.
worksheet.protect()
# Write a locked and unlocked cell.
worksheet.write('A1', 'Cell B1 is locked. It cannot be edited.')
worksheet.write('A2', 'Cell B2 is unlocked. It can be edited.')
worksheet.write_formula('B1', '=1+2') # Locked by default.
worksheet.write_formula('B2', '=1+2', unlocked)
workbook.close()
想要了解更多详细信息,可以查看文档中的 protect() 部分。