【问题标题】:Searching through an Excel Sheet and Printing Data in Python在 Python 中搜索 Excel 工作表并打印数据
【发布时间】:2015-07-23 17:48:56
【问题描述】:

我正在尝试使用 Python 搜索 Excel 文件并打印与用户搜索的单元格的值相对应的数据。

我有一个 Excel 文件,其中一列中列出了美国的每个邮政编码,接下来的四列是与该邮政编码相关的信息,例如它所在的州、将物品运送到那里的价格、等等。我希望用户能够搜索特定的邮政编码并让程序打印出相应单元格中的信息。

这是我目前所拥有的:

from xlrd import open_workbook

book = open_workbook('zip_code_database edited.xls',on_demand=True)
prompt = '>'
print "Please enter a Zip Code."
item = raw_input(prompt)
sheet = book.sheet_by_index(0)
for cell in sheet.col(1): #
    if sheet.cell_value == item:
        print "Data: ",sheet.row

非常感谢任何和所有帮助!

【问题讨论】:

  • 您有什么具体问题吗?你期望你的代码做什么?它实际上做了什么?您是否尝试过手动逐行运行代码进行调试?

标签: python excel


【解决方案1】:

sheet.cell_value 是一个永远不会等于item 的函数。你应该尝试使用cell.value访问

例子-

for cell in sheet.col(1): 
    if cell.value == item:
        print "Data: ",cell

【讨论】:

    【解决方案2】:

    我没有使用过您正在使用的模块 xlrd,但如果您只使用普通的 python dictionary 来完成这项工作并创建一个包含加载的字典。我假设您熟悉以下解决方案的 python dictionary

    您将使用邮政编码作为键,将其他 4 个数据字段用作字典的值(我假设下面有一个 .csv 文件,但您也可以使用制表符分隔或其他单个空格)。调用以下文件make_zip_dict.py

    zipcode_dict = {}
    myzipcode = 'zip_code_database edited.xls'
    
    with open(myzipcode, 'r') as f:
    
        for line in f:
    
            line     = line.split(',')  # break the line into the 5 fields
            zip_code = line[0] # assuming zips are the first column 
            info     = ' '.join(line[1:])  # the other fields turned into a string with single spaces
    
            # now for each zip, enter the info in the dictionary:
            zipcode_dict[zip_code] = info
    

    将此文件保存到与'zip_code_database edited.xls' 相同的目录中。现在,要以交互方式使用它,导航到目录并启动 python 交互会话:

    >>> import make_zip_dict as mzd  # this loads the module and the dict
    >>> my_zip = '10001'  # pick some zip to try out
    >>> mzd.zipcode_dict[my_zip]  # enter it into the dict
    'New York City NY $9.99 info4'  # it should return your results
    

    您可以通过输入所需的邮政编码在命令行上以交互方式使用它。您还可以添加一些花哨的花里胡哨,但这会很快吐出信息,而且它应该非常轻巧且快速。

    【讨论】:

      猜你喜欢
      • 2019-01-27
      • 2020-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      • 2021-10-23
      • 1970-01-01
      相关资源
      最近更新 更多