Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export Plotly Dash datatable output to a CSV by clicking download link

Hi Anyone able to help advise? I have an issue trying to export the data being populated from data table filtered from drop down selection upon clicking on download link to a CSV file.

Error gotten after clicking on the Download Link

csv_string = dff.to_csv(index=False, encoding='utf-8')
AttributeError: 'str' object has no attribute 'to_csv'

And the file that was downloaded is a file containing html code.

enter image description here

Code snippets below

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output,State
import plotly.graph_objs as go
import dash_table
import dash_table_experiments as dt

from urllib.parse import quote

import flask

import pandas as pd

import numpy as np
import pyodbc 

app.layout = html.Div([
    
    html.H3("Sales Summary Report"),  
        dcc.Graph(
            figure={
                "data": [
                    {
                        "x": df["Sales_RANGE"],
                        "y": df['count'],
                        "name":'No of Cust',
                        "type": "bar",
                        "marker":{'color':'rgba(26, 118, 255, 0.5)',
                       #'line':{
                      #  'color':'rgb(8,48,107)',
                      #  'width':1.5,
                      #  }
                        }
                        
                    }
                ],
                "layout": {
                    "xaxis": {"automargin": True},
                    "yaxis": {
                        "automargin": True,
                       # "title": {"text": column}
                    },
                    "height": 250,
                    "margin": {"t": 10, "l": 10, "r": 10},
                },
            },
        )
 ,
     html.Label(["Select Sales range to view", 
                dcc.Dropdown(
                    id="SalesRange",
                    style={'height': '30px', 'width': '55%'},
                    options=[{'label': i,
                              'value': i
                             } for i in Sales_Range_Options],
                             value='All'                    
                )
               ]),

 
    #TABLE
    html.H5("Details"),

    html.Div(id='detailsresults')  , 
    html.A('Download Data',
        id='download-link',
        download="rawdata.csv",
        href="",
        target="_blank"
    )
  
])


def generate_table(dataframe):
    '''Given dataframe, return template generated using Dash components
    '''
    return html.Div( [dash_table.DataTable(
                #id='match-results',

                data=dataframe.to_dict('records'),
                columns=[{"name": i, "id": i} for i in dataframe.columns], 
                editable=False
                ),
                   html.Hr()
        ])

                  
@app.callback(
    Output('detailsresults', 'children'),
    [
        Input('SalesRange', 'value'),
    ]
)


def load_results(SalesRange):
    if SalesRange== 'All':
        return  generate_table(df)
    else:
        results = df[df['SALES_RANGE'] == SalesRange]
        return generate_table(results)


@app.callback(
    dash.dependencies.Output('download-link', 'href'),
    [dash.dependencies.Input('SalesRange', 'value')])
def update_download_link(SalesRange):
    dff = load_results(SalesRange)
    csv_string = dff.to_csv(index=False, encoding='utf-8')
    csv_string = "data:text/csv;charset=utf-8,%EF%BB%BF" + quote(csv_string)
  
    return csv_string
like image 757
Hui Mien Lim Avatar asked Apr 14 '20 08:04

Hui Mien Lim


People also ask

How do I download a file from Plotly?

Download | Dash for Python Documentation | Plotly dcc.Download With the dcc.Downloadcomponent, you can allow users to directly download files from your app. These files include (but are not limited to) spreadsheets, images, text files, etc. dcc.Downloadopens a download dialog when the dataproperty changes.

How to use CSV export in dash_table?

CSV export is officially supported by dash_table.DataTable. You simply need to specify export_format='csv' when you build the table: dash_table.DataTable ( id="table", columns= [ {"name": i, "id": i} for i in df.columns], data=df.to_dict ("records"), export_format="csv", )

How do I view and export figures in Plotly?

Plotly figures are interactive when viewed in a web browser: you can hover over data points, pan and zoom axes, and show and hide traces by clicking or double-clicking on the legend. You can export figures either to static image file formats like PNG, JPEG, SVG or PDF or you can export them to HTML files which can be opened in a browser.

How to export filtered data from a data table to CSV?

Exporting the filtered data table requires a callback. Since the data exported should match the data displayed in the data table, simply reuse the data table callback and make a few adjustments. The bold text is what was changed from the copied callback. Change the output value, the function name, and return the csv file using pandas and urllib.


1 Answers

CSV export is officially supported by dash_table.DataTable. You simply need to specify export_format='csv' when you build the table:

dash_table.DataTable(
    id="table",
    columns=[{"name": i, "id": i} for i in df.columns],
    data=df.to_dict("records"),
    export_format="csv",
)

Here's a complete example app.py that you can run:

import dash
import dash_table
import dash_html_components as html
import pandas as pd

df = pd.DataFrame(
    [
        ["California", 289, 4395, 15.3, 10826],
        ["Arizona", 48, 1078, 22.5, 2550],
        ["Nevada", 11, 238, 21.6, 557],
        ["New Mexico", 33, 261, 7.9, 590],
        ["Colorado", 20, 118, 5.9, 235],
    ],
    columns=["State", "# Solar Plants", "MW", "Mean MW/Plant", "GWh"],
)

app = dash.Dash(__name__)
server = app.server

app.layout = dash_table.DataTable(
    id="table",
    columns=[{"name": i, "id": i} for i in df.columns],
    data=df.to_dict("records"),
    export_format="csv",
)

if __name__ == "__main__":
    app.run_server(debug=True)

You will see a button above the table: enter image description here

like image 108
xhlulu Avatar answered Oct 14 '22 06:10

xhlulu