Reputation: 11
Is there a way other than using pyautogui
to make Python paste from clipboard (ctrl + v) in a new or an existing .xlsx file?
The output from another application previously run is stored in the clipboard.
Everything works OK when I manually open the workbook and paste data, I just want to automate it.
Upvotes: 0
Views: 3553
Reputation: 29580
You can grab the string from the clipboard using pyperclip
:
The purpose of Pyperclip is to provide a cross-platform Python module for copying and pasting text to the clipboard.
... To paste the text from the clipboard, call
pyperclip.paste()
and the text will be returned as a string value.
import pyperclip
pyperclip.paste()
Since it's now a string, you can then use any of the existing Python-based Excel libraries to put that string into your workbook (or any file I/O libraries if it's not specific to Excel files).
Here's an example using openpyxl
(mostly based on the Simple usage - Write a workbook example from the openpyxl
docs):
import pyperclip
from openpyxl import Workbook
# Create a new workbook
wb = Workbook()
wb_filename = "example.xlsx"
# Create a new sheet
ws = wb.create_sheet(title="example")
# Paste the contents to this new sheet
# Here, let's just paste into cell A1
ws["A1"] = pyperclip.paste()
# Finally save the workbook
wb.save(filename=wb_filename)
Upvotes: 1
Reputation: 1
you can dump copied data to excel directly using pandas
import pandas as pd
import xlsxwriter
df = pd.read_clipboard()
df.to_excel(output_xl, sheet_name ='your sheet_name', engine ='xlsxwriter', index=False)
Upvotes: 0
Reputation: 385
execute
pip install clipboard
in the terminal
Easy usage
import clipboard
clipboard.copy("abc") # now the clipboard content will be string "abc"
text = clipboard.paste() # text will have the content of clipboard
Upvotes: 0
Reputation: 29580
(This answer was copied from OP's edit that added "SOLVED" into the question)
I have managed to solve this by using Get-Clipboard > filename.csv by using the Windows PowerShell.
Upvotes: 0