I would like to use the TextInput from the user to download the number of specified rows in a CSV file on clicking the download Button. I have used the code from here: How to Download a DataTable as a .csv in a bokeh_server app
In the code below the value of the argument “dwnld_n” doesn’t get updated as per the updated value of the “dwnld_top.value” instead it remains as the initial value of “dwnld_top.value” which in this case is 3.
from bokeh.models.callbacks import CustomJS
import pandas as pd
from bokeh.plotting import ColumnDataSource
from bokeh.models.widgets import Button, DataTable, TableColumn
from bokeh.models import TextInput
from bokeh.layouts import row, column
from bokeh.io import curdoc
js_dwnld = """
var top_n = dwnld_n;
var csv = src.data;
var filetext = 'a,b,c\\n';
for (i=0; i<top_n; i++) {
var currRow = [csv['a'][i].toString(),
csv['b'][i].toString(),
csv['c'][i].toString().concat('\\n')]
var joined = currRow.join();
filetext = filetext.concat(joined);
}
var filename = 'results.csv';
var blob = new Blob([filetext], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
}
else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
"""
data = pd.DataFrame({'a':[1,2,3], 'b':[2,3,4], 'c':['d','e','f']})
tab_data = ColumnDataSource(data)
tab_cols = [TableColumn(field="a", title="a"), TableColumn(field="b", title="b"), TableColumn(field="c", title="c")]
tab = DataTable(source=tab_data, columns=tab_cols)
dwnld_top = TextInput(value=str(len(data)), title="Number of rows to download")
dwnld = Button(label='Download')
dwnld.js_on_click(CustomJS(args=dict(src=tab_data, dwnld_n=int(dwnld_top.value)), code=js_dwnld))
layout = row(column(dwnld_top, dwnld), tab)
curdoc().add_root(layout)
It would be great if there is a solution to download the data ordered as per the user’s sort applied on the DataTable.
Link to question on stackoverflow: https://stackoverflow.com/questions/62653275/how-do-i-use-a-textinput-from-the-user-to-download-in-a-csv-file-the-top-n-rows
I would greatly appreciate any help on this. Thanks!