如何修改PyScript代码实现两个Excel文件的双输入查询功能?
解决方案
1. 更新 test.toml 配置文件
在原有的[[fetch]]条目下添加第二个Excel文件的获取配置,PyScript通过数组形式支持多资源获取:
packages = ["pandas","openpyxl"] [[fetch]] from="./path/spreadsheet1.xlsx" [[fetch]] from="./path/spreadsheet2.xlsx" # 替换为你的第二个Excel文件实际路径
2. 修改Python函数逻辑
扩展pytest函数,新增第二个输入框的读取、第二个Excel文件的查询逻辑,同时添加基础异常处理避免匹配失败时崩溃:
import js import pandas as pd from pyscript import document def pytest(event): # 处理第一个查询逻辑(保留原有功能) test1a = document.querySelector("#test1i") test1b = test1a.value df1 = pd.read_excel('spreadsheet1.xlsx', sheet_name='sheet1') try: test1c = df1.loc[df1['column1'] == test1b, 'column2'].values[0] except IndexError: test1c = "无匹配结果" test1d = document.querySelector("#test1o") test1d.value = test1c # 新增第二个查询逻辑 test2a = document.querySelector("#test2i") test2b = test2a.value df2 = pd.read_excel('spreadsheet2.xlsx', sheet_name='sheet1') # 替换为第二个Excel的实际表名 try: # 替换为第二个Excel的真实列名 test2c = df2.loc[df2['column1'] == test2b, 'column2'].values[0] except IndexError: test2c = "无匹配结果" test2d = document.querySelector("#test2o") test2d.value = test2c
3. HTML部分无需修改
原有的HTML结构已经包含test2i输入框和test2o输出框,保持现有代码即可。
注意事项
- 确保
test.toml中第二个Excel文件的路径和实际文件位置一致 - 替换代码中
column1、column2为第二个Excel文件的真实列名 - 异常处理逻辑可根据需求调整,比如自定义提示文本
内容的提问来源于stack exchange,提问作者warrenjb
相关产品推荐
相关产品推荐

