【问题标题】:Get excel cell address in Python 2 using openpyxl使用 openpyxl 在 Python 2 中获取 excel 单元格地址
【发布时间】:2017-11-16 09:35:20
【问题描述】:

我有以下场景:

  1. 读取所有活动行的 A 列的 excel 文件
  2. 运行 if else 语句:如果列 A == 'registered',什么也不做,只读取下一行。否则,获取单元格地址(不是值)并执行一些操作

例如,这里是我的“sample.xlsx”:

[第 1 行] A1=已注册 B1=user1

[第 2 行] A2=已注册 B2=user2

[第 3 行] A3=null B3=user3

我的代码应该忽略第 1 行和第 2 行并继续执行第 3 行。在第 3 行中,我应该得到“A3”并执行一些操作。

from openpyxl import load_workbook
book = load_workbook(filename='sample.xlsx')
sheet = book.active
first_column = sheet['A']

for x in xrange(len(first_column)):
    status = first_column[x].value

    if status == 'registered':
      #enter code to just proceed with the next row

    else:
      #enter code to get the column cell range and do some actions

book.save('sample.xlsx')

我被场景 2 卡住了,我是 python 的新手,我有一个使用 FileScanner 的 java 代码,但我在 Python 2 中需要它。感谢您的帮助。

更新: 我在下面已经有了答案,只是想知道是否还有其他方法?

【问题讨论】:

  • 能否分享您想要的输出,其他人会很容易提供帮助。
  • 看看,我刚刚发布了答案。

标签: python excel python-2.7 openpyxl


【解决方案1】:

看看


import openpyxl

wb = openpyxl.load_workbook('sample.xlsx')
ws = wb.active

for row in ws.iter_rows('A{}:A{}'.format(ws.min_row,ws.max_row)):
   for cell in row:
     if cell.value != "registered":
        print cell.column
        print cell.row
        ## further processing here #######

无需为显式行迭代编写逻辑,此for 循环将处理该问题。

希望对你有帮助:)

【讨论】:

  • iter_rows() 不需要使用 A1:D4 坐标
  • @CharlieClark 那么请帮助我采用替代和最佳方法
【解决方案2】:

到目前为止,我已经尝试过这些。还有其他方法吗?

from openpyxl import load_workbook
book = load_workbook(filename='sample.xlsx')
sheet = book.active
first_column = sheet['A']
checker = 'false'

for x in xrange(len(first_column)):
    status = first_column[x].value
    xaddress = first_column[x].column
    yaddress = first_column[x].row
    celladdress = xaddress+str(yaddress)


    if status != 'registered':
        print celladdress
        checker == 'true'
        break

if checker == 'true':
    #... my actions here ....

这是我的“sample.xlsx”:

[第 1 行] A1=已注册 B1=user1

[第 2 行] A2=已注册 B2=user2

[第 3 行] A3=null B3=user3

输出:A3

【讨论】:

    【解决方案3】:

    阅读documentation 总是有帮助的

    for cell in ws['A']:
        pass
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      • 2015-01-31
      • 2017-02-12
      • 2012-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多