Python(Pywin32)引用自己的单元格/水平移动

所以,请不要告诉我谷歌或研究或阅读任何东西,过去几天我一直这样做,如果我看到有人再说一遍,会感到恼火。

我的问题:我正在使用pywin32和python 2.7.8与(已经存在的)Excel工作表进行通信。 我用它来logging我的工作时间和赚取的钱等。我已经运行到可以打开工作簿,find我现有的条目下的下一个空单元格,并在该单元格中写入date。 我的问题在于我需要水平导航。 我想程序自动运行,所以我不会总是知道单元格的数量。 例如,我目前的细胞是18,1。 我需要移动到18,2 18,3 18,4和18,5。 但是下次我运行这个脚本,我可能需要19,2 …等等

我怎样才能做到这一点? 有没有办法返回当前单元格? 码:

import win32com.client as win32 import os, time xl = win32.Dispatch('Excel.Application') xl.visible = True xl.Workbooks.Open(os.path.join('C:\\Users\\[REDACTED]\\Desktop', '[REDACTED].xls')) xlSheet = xl.Sheets(1) activecell = xlSheet.Cells(1,1) def GetEmptyCell(): global activecell activecell = xlSheet.Cells(1,1) for c in range(1,99,1): if activecell.Value == None: print 'Empty cell' activecell = xlSheet.Cells(c,1) print '(' + str(c) + ',1)' return activecell elif activecell.Value != None: c += 1 activecell = xlSheet.Cells(c,1) print 'Full cell, next' GetEmptyCell() def WriteToEmpty(): global activecell global HoursWorked global GrossIncome global NetIncome HoursWorked = raw_input('Input amount of hours worked: ') GrossIncome = float(HoursWorked) * 9.15 NetIncome = float(GrossIncome) * 0.86233 print 'Money Made: ' + str(GrossIncome) + ' Take Home: ' + str(NetIncome) activecell.Value = time.strftime('%a') + ' ' + time.strftime('%m') + '/' + time.strftime('%d') #HELP FROM HERE WriteToEmpty()`` 

有几十种方法来达到你想要的。 如果在列A中有连续的数据,则可以使用xl.range(“A1”)。end(xldown).offset(1,0).address之类的值来获取下一个空行中第一个单元格的地址。 或者你可以使用xl.range(“A1”)。currentregion和偏移量。 就个人而言,我可能只是把当前的区域放入一个数组,然后从那里工作,然后将数组转储回工作表,但这总是我的偏好,大多数人似乎更喜欢在工作表上工作。