I'm using openpyxl library to do some excel cut/paste operations on spreadsheets.
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. 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.

However, any active_row's value greater than 18 results in the problem. 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.
Is there any way to change the view with using openpyxl?
Scrolling is done by adjusting the openpyxl.worksheet.views.SheetView.topLeftCell variable.
You can scroll to your coords variable with:
worksheet.sheet_view.topLeftCell = coords
You can find more details in the openpyxl documentation.
With openpyxl 2.6.2 you have to set activeCell and sqref like this:
ws.views.sheetView[0].selection[0].activeCell = 'B15'
ws.views.sheetView[0].selection[0].sqref = 'B15'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With