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

使用Python读取Excel内容时遭遇Investment未定义错误求助

解决“Investment undefined”错误

错误原因很明确:你在代码里调用了Investment()类,但完全没有定义这个类,Python找不到对应的类定义,因此抛出未定义错误。

修复要点:

  • 先定义Investment类,匹配你传入的两个参数,给类添加对应属性
  • 用os.path.join拼接文件路径,避免不同操作系统下的路径分隔符问题
  • 不要用list作为变量名(这是Python内置类型),换成更具语义的名称

修改后的完整代码:

import xlrd
import os

# 定义Investment类,适配你传入的两个参数
class Investment:
    def __init__(self, item_name, item_value):
        self.item_name = item_name
        self.item_value = item_value
        # 可根据实际需求添加更多属性或方法

class datafromexcel:
    def __init__(self) -> None:
        rootPath = os.getcwd()
        # 用os.path.join拼接路径,适配Windows/Linux不同系统
        loc = os.path.join(rootPath, "Investment.xlsx")
        
        wb = xlrd.open_workbook(loc) 
        sheet = wb.sheet_by_index(0) 
        # 替换内置类型list的变量名,避免冲突
        investment_list = []  
        for i in range(sheet.nrows): 
            investment_list.append(Investment(sheet.cell_value(i, 0), sheet.cell_value(i, 1)))
        print("Successfully retrieved all excel data")

# 实例化类执行逻辑
if __name__ == "__main__":
    datafromexcel()

额外提示:

  • 可以把Investment类里的item_name和item_value改成实际业务对应的名称(比如product和amount),让代码更易读
  • 如果Excel第一行是表头,循环时可以从i=1开始,跳过表头行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:36:08