我有一个数据框,如下面的代码所示。我只想锁定页眉(第一行),然后让用户更改其余单元格。根据下面的代码,它确实锁定了标题,并使我能够更改“日期”列以外的所有列的值。我无法更改日期列的值。它也应该允许我更改日期列的值
import pandas as pd
df = pd.DataFrame({'Data1': [10, 20, 30],
'Data2': [11, 21, 31],
'Date': ["",
"",
pd.to_datetime('today')]})
writer = pd.ExcelWriter('pandas_filter.xlsx', engine='xlsxwriter', )
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
unlocked = workbook.add_format({'locked': False})
locked = workbook.add_format({'locked': True})
worksheet.protect()
for row in range(1, 150):
worksheet.set_row(row, None, unlocked)
writer.save()
答案 0 :(得分:0)
在XlsxWriter中,单元格格式将覆盖行格式,而行格式将覆盖列格式。
日期时间单元格未解锁的原因是由于Pandas对这些单元格应用了单元格格式(对于日期格式),因此行格式被忽略/覆盖。
避免这种情况的唯一方法是与其他数据框数据分开写入(或覆盖)日期单元格数据,并应用未锁定的日期格式。像这样:
import pandas as pd
df = pd.DataFrame({'Data1': [10, 20, 30],
'Data2': [11, 21, 31],
'Date': [pd.to_datetime('today'),
pd.to_datetime('today'),
pd.to_datetime('today')]})
writer = pd.ExcelWriter('pandas_filter.xlsx', engine='xlsxwriter', )
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
unlocked = workbook.add_format({'locked': False})
locked = workbook.add_format({'locked': True})
# Write the 'Date' column data.
worksheet.set_column('C:C', 20)
unlocked_date_format = workbook.add_format({'num_format': 'yyyy-mm-dd',
'locked': False})
worksheet.write_column('C2', df['Date'], unlocked_date_format)
worksheet.protect()
for row in range(1, 150):
worksheet.set_row(row, None, unlocked)
writer.save()
修改后的输出: