简体   繁体   English

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

[英]Python openpyxl How to SET the active or selected cell

In Python with openpyxl I'd like to change the active cell when the user opens the spreadsheet.在带有 openpyxl 的 Python 中,我想在用户打开电子表格时更改活动单元格。

This produces 'A1':这会产生“A1”:

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

This produces an error when the file is opened (Corrupted file):打开文件时会产生错误(损坏的文件):

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

How can I set the active/selected cell to something other than A1?如何将活动/选定单元格设置为 A1 以外的内容?

For openpyxls version 2.3.2 I got this to work: 对于openpyxls版本2.3.2,我可以使用它:

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

Hope this helps someone. 希望这对某人有帮助。

Based on the accepted answer and the answer by BryanSJT, I created this loop which should set all selections correctly to A1根据接受的答案和 BryanSJT 的答案,我创建了这个循环,它应该将所有选择正确设置为 A1

for selection in ws.views.sheetView[0].selection:
        selection.activeCell = "A1"
        selection.sqref = "A1"

If you got openpyxl version 2.5.4 or later, try typing below to set active cell 如果您拥有openpyxl 2.5.4或更高版本,请尝试在下面输入内容以设置活动单元格

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

assume ws is the worksheet you use, and you want to set cell A4 active. 假设ws是您使用的工作表,并且您想要将单元格A4设置为活动状态。 Make sure you save the spreadsheet in your code. 确保将电子表格保存在代码中。

I'm using openpyxl version 3.0.7 and found that for an excel file I have it was necessary to also do the same definition for selection[1].我正在使用 openpyxl 版本 3.0.7,发现对于一个 excel 文件,我有必要对选择 [1] 进行相同的定义。

worksheet.views.sheetView[0].selection[0].activeCell = 'A1'
worksheet.views.sheetView[0].selection[0].sqref = 'A1'

worksheet.views.sheetView[0].selection[1].activeCell = 'A1'
worksheet.views.sheetView[0].selection[1].sqref = 'A1'

or或者

data_sheet.sheet_view.selection[0].activeCell = 'A1'
data_sheet.sheet_view.selection[0].sqref = 'A1'

data_sheet.sheet_view.selection[1].activeCell = 'A1'
data_sheet.sheet_view.selection[1].sqref = 'A1'

I hope this helps someone.我希望这可以帮助别人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM