Python xlwt - 使列只读(单元格保护)

5 投票
1 回答
3880 浏览
提问于 2025-04-17 08:27

有没有办法让Python的xlwt库中的某个特定单元格变成只读或写保护的?

我知道有一个叫cell_overwrite_ok的标志,它可以防止覆盖所有单元格的内容,但我想知道能不能对每个单元格单独设置这个功能。

谢谢,

Sun

1 个回答

9

Excel单元格有一个锁定属性,默认是开启的。不过,这个属性只有在工作表的保护属性也设置为True时才会生效。如果工作表没有被保护,锁定属性就会被忽略。

所以,你的问题其实不是问如何让单元格只读。更准确的说法是如何在保护工作表后让单元格可编辑

...给你一个示例:

from xlwt import Workbook, Worksheet, easyxf

# ...

# Protect worksheet - all cells will be read-only by default
my_worksheet.protect = True  # defaults to False
my_worksheet.password = "something_difficult_to_guess"

# Create cell styles for both read-only and editable cells
editable = easyxf("protection: cell_locked false;")
read_only = easyxf("")  # "cell_locked true" is default

# Apply your new styles when writing cells
my_worksheet.write(0, 0, "Can't touch this!", read_only)
my_worksheet.write(2, 2, "Erase me :)", editable)

# ...

单元格样式(easyxf类)也可以用来设置背景颜色、字体粗细等。

祝好。

撰写回答