You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Python Dash中to_html生成的DataFrame设置单列可编辑?

实现colH列可编辑的方案

pandas的to_html方法没有直接支持列级可编辑的参数,我们可以通过自定义格式化函数,把colH列的单元格转换成可编辑的<input>标签来实现需求。

修改步骤:

  1. 新增一个针对colH列的格式化函数,将单元格内容转为带默认值的输入框
  2. 把这个函数添加到格式字典format_dict中,对应colH列

修改后的完整代码:

import pandas as pd
from IPython.core.display import display,HTML
import os

pd.set_option('display.max_colwidth', 0)
MP = 'GB'

df = pd.DataFrame(
    [
        (1, 'Hello', 158, True, 'Extract-Text-from-Image-using-Python-840x400',""),
        (2, 'Hey', 567, False, 'sampletext1-ocr',""),
        (3, 'Hi', 123, False, 'sampletext2-ocr',""),
        (4, 'Howdy', 578, True, 'sampletext3-ocr',""),
        (5, 'Hello', 418, True, 'image-10',""),
        (6, 'Hi', 98, False, 'image-9',""),
    ],
    columns=['colA', 'colB', 'colC', 'colD', 'colE', 'colH']
)


def categorise(row):
    return f"https://pyshark.com/wp-content/uploads/2022/05/{row['colE']}.png"

df['colF'] = df.apply(lambda row: categorise(row), axis=1)

images1 = df['colF'].values.tolist()
df['colG'] = images1

# convert your links to html tags 
def path_to_image_html(path):
    return '<img src="'+ path + '" width="60" >'

# 新增:colH列的可编辑格式化函数
def editable_cell(value):
    return f'<input type="text" value="{value}" style="width:100%;border:none;" />'

pd.set_option('display.max_colwidth', None)

image_cols = ['colG']  #<- define which columns will be used to convert to html

# Create the dictionary to be passed as formatters
format_dict = {}
for image_col in image_cols:
    format_dict[image_col] = path_to_image_html

# 新增:将colH的格式化函数加入字典
format_dict['colH'] = editable_cell

a = HTML(df.drop(['colF'], axis=1).to_html(escape=False ,formatters=format_dict))

with open("assets/data.html", "w") as file:
    file.write(a.data)

说明:

  • 自定义的editable_cell函数会把colH的每个单元格转为一个文本输入框,默认值为原单元格内容,样式设置为无边框、宽度100%,和原表格单元格风格一致
  • 生成的data.html中,只有colH列的单元格可以直接编辑,其他列保持原有状态
  • 如果需要保存编辑后的数据,你需要额外添加JavaScript代码来捕获输入框的变化并提交,或者结合后端逻辑处理

内容的提问来源于stack exchange,提问作者Sanket Sathe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 06:45:35