简体   繁体   English

python openpyxl在所选单元格上设置光标

[英]python openpyxl set cursor on the chosen cell

I'm using openpyxl library to do some excel cut/paste operations on spreadsheets. 我正在使用openpyxl库在电子表格上执行一些excel剪切/粘贴操作。 Let's say that my operations produce the following data (please use it for reproducibility purposes): 假设我的操作产生了以下数据(请出于重复性目的使用它):

col1;col2
1;0,17153686
2;0,615324797
3;0,573701744
4;0,503462355
5;0,154284926
6;0,10027259
7;0,926526263
8;0,871108863
9;0,048035143
10;0,38731583
11;0,48529708
12;0,901046699
13;0,985505734
14;0,606868435
15;0,280662943
16;0,356188065
17;0,102727139
18;0,800757985
19;0,767509347
20;0,418477445
21;0,751892035
22;0,959923786
23;0,524754643
24;0,014140778
25;0,267427799
26;0,666726192
27;0,019314009
28;0,764133187
29;0,587031993

This is the code that chooses the active cell according to an argument given: 这是根据给定参数选择活动单元格的代码:

from openpyxl import load_workbook, Workbook

def set_active_cell(new_file_name, active_row):
    print(active_row)
    workbook = load_workbook(new_file_name)
    sheet = workbook.get_sheet_names()[0] #get the name of first sheet
    worksheet = workbook.get_sheet_by_name(sheet)
    coords = "A" + str(active_row)
    print(coords)
    # worksheet.cell(row=active_row, column=1)
    worksheet.sheet_view.selection[0].activeCell = coords
    worksheet.sheet_view.selection[0].sqref = coords
    workbook.save(new_file_name)

if __name__ == "__main__":
    set_active_cell("data.xlsx", 28)

As you can see on the attached image my default view encompasses the first 18 rows. 如您所见,我的默认视图包含前18行。 If active_row is smaller or equal to 18 I get what I want: I can see the active cell in my starting view of the Excel file. 如果active_row小于或等于18,我将得到所需的信息:我可以在Excel文件的起始视图中看到活动单元格。

在此处输入图片说明

However, any active_row 's value greater than 18 results in the problem. 但是,任何active_row的值大于18都会导致问题。 The active cell is chosen correctly, but my starting view is still the first 18 rows and I need to scroll down in order the reach the active cell. 正确选择了活动单元,但是我的起始视图仍然是前18行,我需要向下滚动才能到达活动单元。

Is there any way to change the view with using openpyxl ? 有什么办法可以使用openpyxl更改视图?

Scrolling is done by adjusting the openpyxl.worksheet.views.SheetView. 通过调整openpyxl.worksheet.views.SheetView来完成滚动。 topLeftCell variable. topLeftCell变量。

You can scroll to your coords variable with: 您可以使用以下方法滚动到您的coords变量:

worksheet.sheet_view.topLeftCell = coords

You can find more details in the openpyxl documentation. 您可以在openpyxl文档中找到更多详细信息

With openpyxl 2.6.2 you have to set activeCell and sqref like this: 使用openpyxl 2.6.2,您必须像这样设置activeCellsqref

ws.views.sheetView[0].selection[0].activeCell = 'B15'
ws.views.sheetView[0].selection[0].sqref = 'B15'

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

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