Python openpyxl 如何设置活动或选中的单元格

Python openpyxl How to SET the active or selected cell

在使用 openpyxl 的 Python 中,我想在用户打开电子表格时更改活动单元格。

这会产生 'A1':

 print("Active Cell: " + WorkSheetOne.sheet_view.selection[0].activeCell)

打开文件时出现错误(损坏的文件):

 WorkSheetOne.sheet_view.selection[0].activeCell = 'A4'

如何将 active/selected 单元格设置为 A1 以外的内容?

对于 openpyxls 版本 2.3.2,我让它工作:

 WorkSheetOne.sheet_view.selection[0].activeCell = 'A4'
 WorkSheetOne.sheet_view.selection[0].sqref = 'A4'

希望这对某人有所帮助。

如果您有 openpyxl 版本 2.5.4 或更高版本,请尝试在下面输入以设置活动单元格

ws.cell(row=4, column=1)
wb.save("spreadsheet.xlsx")

假设 ws 是您使用的工作表,并且您想要将单元格 A4 设置为活动状态。确保将电子表格保存在代码中。