Copying Pandas DataFrame to clipboard

Wondering if anyone else has run into a similar issue. I have a dashboard that I want to for exploring data at my job. When I run a local instance I can get something like this to run:

def copy_fun(event):
    df_temp = panel_df_object_name[1][0].object
    dt_temp.to_clipboard()

copy_button.on_click(copy_fun)

I was hoping to get this hosted on our server and this is the only bit of functionality that doesn’t seem to carry over (pushing data from the server to a local user on their web browser). I’ve seen some forum posts from Marc going over some simple JS to copy from one input box to another, but can’t seem to rework that to fit my use case here. Anyone have any ideas?

1 Like

You will need to convert your data into a tab separated text string. You can either do that on the python or the javascript side. In the example below I do that on the javascript side for efficiency reasons

import panel as pn
import param

class CopyToClipboardButton(pn.reactive.ReactiveHTML):
    value = param.DataFrame()
    clicks = param.Integer()

    _template = """
    <div class="bk bk-btn-group">
    <button id='copy' class="bk bk-btn bk-btn-default" type="button" onclick='${script("click")}' style='height:100%;width:100%'>{{name}}</button>
    </div>
"""
    _scripts = {
        "click": """
data.clicks+=1

header = Object.keys(data.value)
values = Object.values(data.value)
function transpose(matrix) {
  return matrix[0].map((col, i) => matrix.map(row => row[i]));
}
values = transpose(values)
arr = [header, ...values]
tab_separated = arr.map(lines => lines.join("\t"))
tsv = tab_separated.join("\\n")
navigator.clipboard.writeText(tsv)   
""",
    }

import pandas as pd
df = pd.DataFrame({"x": [1,2,3]})
button = CopyToClipboardButton(value=df, width=320, sizing_mode="fixed", margin=(5,10), name="Copy")
pn.panel(button).servable()
pn.widgets.Button(name="Normal Button").servable()
2 Likes

Also, I believe Tabulator and Perspective both offer functionality to copy to clipboard.

2 Likes