簡體   English   中英

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'

如何將活動/選定單元格設置為 A1 以外的內容?

對於openpyxls版本2.3.2,我可以使用它:

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

希望這對某人有幫助。

根據接受的答案和 BryanSJT 的答案,我創建了這個循環,它應該將所有選擇正確設置為 A1

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

如果您擁有openpyxl 2.5.4或更高版本,請嘗試在下面輸入內容以設置活動單元格

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

假設ws是您使用的工作表,並且您想要將單元格A4設置為活動狀態。 確保將電子表格保存在代碼中。

我正在使用 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'

或者

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'

我希望這可以幫助別人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM