openpyxl active cell cant copy cell

73 views Asked by At

I need help with a problem I've been having for a while.

I'm creating an automation that copies information from Excel to another application (like Notepad).

At first, I was using Pyautogui to copy and paste, but after a while, it started to fail. Sometimes, it wouldn't copy correctly or wouldn't even press the copy key.

So, I decided to try using Openpyxl to copy just the cell. But I'm having trouble getting it to work.

First, I'm not able to get the cell value correctly. Second, I can't make the automation recognize in real time that the active cell has been changed.

there is the code:

import openpyxl

while True:

   wb = openpyxl.load_workbook('CONEMB_ZLE.xlsx')

   sheet = wb.active
   cell = sheet.active_cell  # Get the active cell object

   print(cell)

   wb.save('CONEMB_ZLE')
   print('salvo')
   wb.close()

Can anyone help me with this?

Thanks in advance!

tried everithing but idk i just need to copy a focused cell and save into a var

2

There are 2 answers

0
UnicornOnAzur On

To access the value in the active cell of a workbook you need just one more line of code value = sheet[cell].value. Furthermore, a small refactoring is needed for the wb.save. The script would then look like this.

import openpyxl

while True:
   wb = openpyxl.load_workbook('CONEMB_ZLE.xlsx')
   sheet = wb.active
   cell = sheet.active_cell  # Get the active cell object
   value = sheet[cell].value
   print(value)

   wb.save('CONEMB_ZLE.xlsx')
   print('salvo')
   wb.close()
0
Victor Roza On

openpyxl is great for manipulating Excel files, but it is not suitable for interacting in real time with open Excel. This means that, if you want to detect which cell is active while working in Excel, openpyxl will not be able to help you directly.

For the problem of not being able to correctly copy or simulate keystrokes with PyAutoGUI, an alternative is to use the pyperclip library to handle copy and paste operations more reliably.

Now, if you really need to detect real-time changes in Excel, like which cell is currently active, you'll need something more specific to interact with Excel while it's running. On Windows, you can use something called COM automation (with the pywin32 library), which allows you to do this kind of interaction.

import openpyxl

wb = openpyxl.load_workbook('CONEMB_ZLE.xlsx')

sheet = wb.active

cell_value = sheet['A1'].value

print(cell_value)

wb.close()