Python xlsx单元格保护(锁定)

时间:2013-03-07 12:53:19

标签: python excel

我需要将列表导出为ex​​cel,并保护一些单元格或列(只读)。

问题是我使用openpyxl python模块写入xlsx,但我认为只有xlwt具有单元保护功能。并且xlwt似乎不支持xlsx。

有人找到了解决方法吗?

1 个答案:

答案 0 :(得分:2)

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()部分。

Cell Protection Example