如何在Python Dash中为选中的CSV文件展示dash_table
解决方案
以下是修改后的完整代码,实现了选中CSV文件后展示带滚动条和分页的数据表格:
from dash import Dash, dcc, html, Input, Output, callback, dash_table import boto3 import pandas as pd # 初始化S3客户端 s3 = boto3.client('s3') response = s3.list_buckets() all_options = {} # 筛选以"ag-"开头的存储桶,最多取5个,每个桶下最多取5个CSV文件 for bucket in response['Buckets']: if bucket["Name"].startswith("ag-") and len(all_options) < 5: try: objects = s3.list_objects_v2(Bucket=bucket['Name']) files = [] if 'Contents' in objects: # 处理桶为空的情况 for obj in objects['Contents']: if obj['Key'].endswith('.csv') and len(files) < 5: files.append(obj['Key']) all_options[bucket['Name']] = files except Exception as e: print(f"获取桶{bucket['Name']}文件失败: {e}") all_options[bucket['Name']] = [] external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = Dash(__name__, external_stylesheets=external_stylesheets) app.layout = html.Div([ dcc.RadioItems( list(all_options.keys()), list(all_options.keys())[0] if all_options else None, # 修复初始值错误 id='buckets-radio', ), html.Hr(), dcc.RadioItems(id='files-radio'), html.Hr(), # 预留表格容器,无需在回调中重定义整体布局 html.Div(id='csv-table-container') ]) @callback( Output('files-radio', 'options'), Input('buckets-radio', 'value')) def set_files_options(selected_bucket): if not selected_bucket: return [] return [{'label': i, 'value': i} for i in all_options[selected_bucket]] @callback( Output('files-radio', 'value'), Input('files-radio', 'options')) def set_files_value(available_options): return available_options[0]['value'] if available_options else None @callback( Output('csv-table-container', 'children'), Input('buckets-radio', 'value'), Input('files-radio', 'value')) def display_csv_table(selected_bucket, selected_file): if not selected_bucket or not selected_file: return html.P("请选择一个CSV文件") try: # 从S3读取CSV文件 obj = s3.get_object(Bucket=selected_bucket, Key=selected_file) df = pd.read_csv(obj['Body']) # 生成带滚动条和分页的DataTable return html.Div([ html.H4(f"{selected_file} 的内容"), dash_table.DataTable( columns=[{"name": col, "id": col} for col in df.columns], data=df.to_dict('records'), # 启用本地分页 page_action='native', page_size=10, # 每页显示10条数据 # 设置表格滚动条 style_table={ 'height': '400px', 'overflowY': 'auto' }, style_cell={'textAlign': 'left'}, style_header={'backgroundColor': 'paleturquoise'}, style_data={'backgroundColor': 'lavender'} ) ]) except Exception as e: return html.P(f"读取文件失败: {str(e)}") if __name__ == '__main__': app.run_server(debug=True)
关键改动说明:
- 修复初始值错误:原代码将单选框初始值设为
0,会导致选中第一个桶时触发错误,改为取all_options的第一个键(若存在)。 - 移除回调内重定义布局的逻辑:Dash布局应在初始化时定义,回调只需返回需更新的组件内容,无需重新设置整个页面布局。
- 添加异常处理:处理桶为空、文件读取失败等场景,返回友好提示信息。
- 配置表格滚动与分页:
- 通过
style_table设置固定高度和overflowY: auto,实现垂直滚动效果 - 开启
page_action='native'启用本地分页,page_size控制每页显示条数
- 通过
- 优化S3资源获取逻辑:增加
'Contents' in objects判断,避免桶为空时抛出KeyError。
内容的提问来源于stack exchange,提问作者Yuva
相关产品推荐
相关产品推荐

