【问题标题】:For loop not work in excel worksheet_pythonFor循环在excel工作表python中不起作用
【发布时间】:2019-12-30 03:11:52
【问题描述】:

现在我使用for循环来检测excel文件中的空单元格。当它找到空白单元格时我需要停止循环。但是我的循环不会停止工作。我需要在找到空白单元格时中断循环。

这是我的代码:

for i in excel:
if i == None:
    print('Finish work')
    break
elif i == '1':
    py.hotkey('Enter')
else:
    py.hotkey('Enter','Tab')
    py.hotkey('tab');py.hotkey('tab');py.hotkey('tab');py.hotkey('tab');py.hotkey('tab');py.hotkey('tab')

这是我的 excel 文件图片: This's my excel File picture i don't have reputation score i can't post picture.

【问题讨论】:

  • 您是否尝试对电子表格中的每一行进行循环,然后在没有更多行有数据时停止?
  • 是的。我的循环在找到空白单元格时不会停止。(或单元格 = B4)
  • 您是否使用 py.hotkey 转到电子表格中的新单元格?
  • 是的。我正在使用 py.hotkey 转到电子表格中的新单元格

标签: python excel python-3.x loops for-loop


【解决方案1】:

你可以用 pylightxl 很容易地做到这一点。如果您所做的只是读取数据(请参阅文档:https://pylightxl.readthedocs.io/en/latest/quickstart.html

import pylightxl as xl

db = pylightxl.readxl('yourExcelFile.xlsx')

# assuming your data is in Sheet1 and column A (you can change this to whatever you need)
for celldata in db.xl('Sheet1').col(1):
    if celldata == '':
        print('Finish work')
        break
    elif celldata == '1':
        # do something
        pass
    else:
        # do something else
        pass

【讨论】:

    【解决方案2】:

    判断 cmets 并进一步了解,您似乎想在 Python 中以某种方式利用这些信息。

    不建议使用 py.hotkey 来跳过行、通过单元格进行制表符等搜索空白。

    您可以轻松地将 xlsx/csv 导入 Python 并使用列表/pandas 等对其进行迭代。这是一个如何将 xlsx 导入 Python 并使用 Pandas 迭代数据的示例。

    # Import Pandas
    import pandas as pd
    
    # Create dataframe referencing Excel file
    
    df = pd.read_excel("spreadsheet.xlsx")
    
    # This is what the dataframe looks like
    
    df
    
    Unnamed: 0 Supplier Name Payment Date  ...  Satang break   Description
    0          17          Mr.A      #######  ...       0     1  Cash advance
    1          21          Mr.B      #######  ...       0     1  Cash advance
    
    [2 rows x 9 columns]
    
    # Iterate over all rows in the dataframe
    
    for index, row in df.iterrows():
        print(row['Supplier Name'], row['Payment Date'])
    
    # Printed result based on row['column name']
    Mr.A #######
    Mr.B #######
    

    还有其他方法可以导入和解析电子表格,不过不妨试试 Pandas!这是一个非常强大的模块,应该能够帮助您完成这个项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-21
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 2015-05-24
      • 1970-01-01
      相关资源
      最近更新 更多