Search code examples
pythonexcelcopyopenpyxlpyperclip

Real-Time Copying and Pasting to Excel


I made this simple program using openpyxl and pyperclip that pastes the clipboard's contents on to successive rows in Excel - so for instance if I copied the word 'hello', it will paste 'hello' on to the cells 'A2, A3, A4...'

However, my main goal is to create a program where I can copy text in real-time and the program pastes it to the cells as so. For example, I copy the text 'hello', the program pastes it onto A2, then I copy the text 'I like python' and it pastes that onto to cell A3 and so on(and then I press a key to end the program when I am done).

Is this possible? If so how can I do this? (I am open to downloading new libraries etc.)

import openpyxl
from openpyxl import Workbook
import pyperclip

wb = Workbook()

column = 'A'
row = 0

# grab the active worksheet
ws = wb.active

#loop through excel rows
for x in range(2,6):
   row = x
   cell = column + str(row)
   ws[cell] = pyperclip.paste()
   
# Save the file
wb.save("sample.xlsx")

Additional Help: In the case, I (with your help) figure out how to do this, I will also appreciate if someone can tell me how to save the cell number/code too. So for e.g. I run the program and paste the respective text on the the cells 'A1, A2, A3...A14.' Is there a way to also save 'A14' into the memory, so the next time I run the program it starts from A14 and pastes accordingly -'A14, A15, A16...'


Solution

  • import openpyxl
    from openpyxl import Workbook
    import pyperclip
    
    
    wb = Workbook()
    
    column = 'A'
    row = 0
    
    # grab the active worksheet
    ws = wb.active
    
    clipboard = ["quote", "random"]
    
    limit = 10
    
    recentcopy = 'a'
    
    x = 1
    while(len(clipboard)<limit):
        recentcopy = pyperclip.paste()
        if(recentcopy != clipboard [x]):
            clipboard.append(pyperclip.paste())
            print(clipboard)
            row = x + 1
            cell = column + str(row)
            ws[cell] = clipboard[x]
            wb.save("heyo.xlsx")
            x = x+1