单击下载链接将 Plotly Dash 数据表输出导出为 CSV [英] Export Plotly Dash datatable output to a CSV by clicking download link

查看:85
本文介绍了单击下载链接将 Plotly Dash 数据表输出导出为 CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮忙提供建议吗?我在尝试将点击下载链接后从下拉选择过滤的数据表中填充的数据导出到 CSV 文件时遇到问题.

点击下载链接后出错

csv_string = dff.to_csv(index=False, encoding='utf-8')AttributeError: 'str' 对象没有属性 'to_csv'

而下载的文件是一个包含html代码的文件.

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

解决方案

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:

这篇关于单击下载链接将 Plotly Dash 数据表输出导出为 CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆