Suppose we have a Python structure representing a table (whichever, eg a list of lists).
Is there an elegant way to programmatically copy that structure into the clipboard, so that it can be correctly pasted as a table, eg in Microsoft Word or Excel? I am looking preferably for a portable solution, otherwise specific solutions for MacOS, Linux and Windows would be appreciated.
To copy a table in the form of a list of lists to the clipboard, first convert it to a string by concatenating values with tabs and rows with new lines:
table = [
list(range(10)),
list(range(11, 21)),
list(range(21, 31)),
]
result = '\n'.join(['\t'.join(map(str, row)) for row in table])
print(result)
This results in:
0 1 2 3 4 5 6 7 8 9
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
There are several ways to copy this to the clipboard. Here is a cross-platform method using tkinter
based on this answer :
from tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append(result)
r.update()
r.destroy()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.