gpt4 book ai didi

python - 无法锁定 Excel 工作表中的列 - xlsxwriter

转载 作者:太空宇宙 更新时间:2023-11-03 20:35:59 34 4
gpt4 key购买 nike

我正在尝试使用 xlsx writer 仅锁定 Excel 工作表的几列。作者已经通过获取 panda 数据帧并使用 to_excel 转换它们来生成工作表。

当使用 xlsxwriter 的简单锁定和保护(发现 here )时,整个工作表最终被锁定,而不是我选择的列中的特定单元格。这是我的代码:

writer = pd.ExcelWriter('workbook.xlsx', engine='xlsxwriter')
df2.to_excel(writer, 'Except', index=False, header=False)
df1.to_excel(writer, 'Rec', index=False, header=False)
workbook = writer.book
rec_sheet = writer.sheets['Rec']
except_sheet = writer.sheets['Except']

# adding lock/unlock capabilities
locked_format = workbook.add_format()
locked_format.set_locked(True)
unlocked_format= workbook.add_format()
unlocked_format.set_locked(False)

# unlocking columns that need to remain unlocked
rec_sheet.set_column('AC:AD', None, unlocked_format)
except_sheet.set_column('AC:AD', None, unlocked_format)

# Enable worksheet protection
except_sheet.protect()
rec_sheet.protect()
#lock columns that need to remain locked
rec_sheet.set_column('A:AB', None, locked_format)
except_sheet.set_column('A:AB', None, locked_format)

我希望最终的工作簿.xlsx 有两张表,其中的列锁定到 AC 列。

最佳答案

它应该可以工作。我在您的示例中添加了一些示例数据帧,并且能够写入单元格 AC3(但不能写入 AB3):

import pandas as pd

df1 = pd.DataFrame([10, 20, 30, 20, 15])
df2 = pd.DataFrame([10, 20, 30, 20, 15])

writer = pd.ExcelWriter('workbook.xlsx', engine='xlsxwriter')
df2.to_excel(writer, 'Except', index=False, header=False)
df1.to_excel(writer, 'Rec', index=False, header=False)
workbook = writer.book
rec_sheet = writer.sheets['Rec']
except_sheet = writer.sheets['Except']

# Adding lock/unlock capabilities.
locked_format = workbook.add_format()
locked_format.set_locked(True)
unlocked_format= workbook.add_format()
unlocked_format.set_locked(False)

# Unlocking columns that need to remain unlocked.
rec_sheet.set_column('AC:AD', None, unlocked_format)
except_sheet.set_column('AC:AD', None, unlocked_format)

# Enable worksheet protection.
except_sheet.protect()
rec_sheet.protect()

# Lock columns that need to remain locked.
rec_sheet.set_column('A:AB', None, locked_format)
except_sheet.set_column('A:AB', None, locked_format)

writer.save()

输出:

enter image description here

关于python - 无法锁定 Excel 工作表中的列 - xlsxwriter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57168006/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com