要在 Dash 中创建超链接的单元格值,可以使用 dash_table.DataTable
组件和 Pandas 数据框来实现。下面是一个示例代码,展示了如何将表格中的某些单元格值转换为超链接。
首先,确保已完成以下安装:
pip install dash
pip install pandas
然后使用以下代码来创建一个具有超链接单元格值的 Dash 应用:
import dash
import dash_table
import pandas as pd
app = dash.Dash(__name__)
# 创建一个示例数据框
data = {
'Name': ['John', 'Jane', 'Tom'],
'Age': [25, 30, 35],
'Website': ['https://www.google.com', 'https://www.facebook.com', 'https://www.linkedin.com']
}
df = pd.DataFrame(data)
# 将“Website”列中的值转换为超链接
df['Website'] = '<a href="' + df['Website'] + '">Website</a>'
app.layout = dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in df.columns],
data=df.to_dict('records'),
# 将“Website”列的解释器设置为“html”,以将单元格渲染为超链接
tooltip_data=[
{
column: {'type': 'text', 'value': value}
for column, value in row.items()
} for row in df.to_dict('rows')
],
tooltip_duration=None,
# 渲染“Website”列为“html”
style_data={
'whiteSpace': 'normal',
'height': 'auto',
'lineHeight': '15px',
'font-size': '12px',
'text-align': 'left',
'overflow': 'hidden',
'textOverflow': 'ellipsis',
},
style_cell={
'minWidth': '180px',
'width': '180px',
'maxWidth': '180px',
},
style_header={
'fontWeight': 'bold'
}
)
if __name__ == '__main__':
app.run_server(debug=True)
上述代码将创建一个 Dash 应用,其中包含一个表格,表格中的“Website”列中的值将被转换为超链接。