简体   繁体   English

如何使用Python Win32com在Excel中查找最后一行是否具有特定列的值

[英]how to find if last row has value for a specific column in Excel using Python Win32com

I have an Excel file and I use python Win32com to operate on it. 我有一个Excel文件,并且使用python Win32com对其进行操作。

how do I check if the last row has value in a specific column ? 如何检查最后一行在特定列中是否有值?

when I try , the nrows is 28, not 23 (the last row have value not empty) 当我尝试时,行数是28,而不是23(最后一行的值不为空)

 used = sht1.UsedRange
 nrows = used.Row + used.Rows.Count - 1

我想找到位置I24

UsedRange is not reliable always when you want to get last row of any specific column. 当您想获取任何特定列的最后一行时,UsedRange并不总是可靠的。 You should use EndXlUp or EndXlDown function. 您应该使用EndXlUp或EndXlDown函数。

Check this below line: 检查以下行:

LastRow = Sheets("Sheet1").Range("A" & Sheets("Sheet1").Rows.Count).End(xlUp).Row

Where, A is the column to get last row. 其中,A是获得最后一行的列。

Also, check this URL: Error in finding last used cell in VBA 另外,请检查以下URL: 在VBA中查找最后使用的单元格时出错

As your are using python win32 com, Endxlup will not work. 由于您使用的是python win32 com,因此Endxlup无法正常工作。 There's one basic thing you can do. 您可以做一件事。 Check the below code: 检查以下代码:

ws = wb.Worksheets('Sheet1')
rw = 2
While ws.cells(rw, 1) <> ""
    rw +=1

Where, rw is the starting row from where you want to start row count. 其中,rw是要从其开始计数的起始行。 1 in (rw, 1) represents column. (rw,1)中的1代表列。 Column A represents A. 列A代表A。

Logic behind this is while loop will run till it does not get blank cell in column A and you will get row count in variable rw 这背后的逻辑是while循环将运行,直到它没有在A列中获得空白单元格并且您将在变量rw中获得行数

xlUp is nothing short of a pre-defined constant. xlUp不缺预定义的常量。

So the most simple way is to type the code in the direct window of the VBE 因此,最简单的方法是在VBE的直接窗口中键入代码

? xlUp

you will see the following result. 您将看到以下结果。

-4162

add the line to your python code 将行添加到您的python代码中

xlUp = -4162

Done! 完成!

.End(xlUp).Row替换为.End(3).Row

i use this stupid way to do . 我用这种愚蠢的方式做。 not sure have problem or not. 不确定是否有问题。 so far work for myself 到目前为止为自己工作

def find_lastrow_oncolumn(worksht, colno):
    used = worksht.UsedRange
    nrows = used.Row + used.Rows.Count - 1
    lastrow_havevalue = 0
    for k in range(nrows):
        if worksht.Cells(nrows-k, colno).Value is not None:
            print worksht.Cells(nrows-k, colno).Value, nrows-k , k
            lastrow_havevalue = nrows-k
            break
    return lastrow_havevalue

I'm currently writing an Excel wrapper, and part of it is this function returning all data from a certain offset to the last row of that column. 我当前正在编写一个Excel包装程序,其中一部分是此函数将所有数据从某个偏移量返回到该列的最后一行。 For example, if I want everything from the 3rd row up till including the last line. 例如,如果我想要从第三行到最后一行的所有内容。 This should work for your problem as well. 这也应该适用于您的问题。 Note where the constant is retrieved from and how all methods are stacked together to get the data and the last row. 注意从何处检索常量,以及如何将所有方法堆叠在一起以获取数据和最后一行。

Key functions: 主要功能:

def get_column_after(self, column, offset):
    for item in self.ws.Range("{0}{1}:{0}{2}".format(column, offset, self.get_last_row_from_column(column))).Value:
        print(item[0])

def get_last_row_from_column(self, column):
    return self.ws.Range("{0}{1}".format(column, self.ws.Rows.Count)).End(win32com.client.constants.xlUp).Row

NOTE: This code is a work in progress and at the moment only supports one worksheet, one workbook per instance. 注意:此代码是一个正在进行的工作,目前仅支持一个工作表,每个实例一个工作簿。 I'm sure you can figure out a way to get this to work in your project though. 我相信您可以找到一种方法使它在您的项目中起作用。

import string
import win32com.client

SOURCE_PATH = "C:\ExternData\somefile.xlsx"
WORKSHEET_NAME = "WS_1"

class ExcelInstance():
    def __init__(self, wb=None):
        self.source_path = SOURCE_PATH
        try:
            self.app = win32com.client.gencache.EnsureDispatch('Excel.Application')
        except:
            print("Application could not be opened.")
            return
        try:
            self.open_workbook()
        except:
            print("Workbook could not be opened.")
            return
        try:
            self.ws = self.wb.Worksheets(WORKSHEET_NAME) 
        except:
            print("Worksheet not found.")
            return
        self.app.Visible = True
        self.app.WindowState = win32com.client.constants.xlMaximized

    def open_workbook(self):
        """
        If it doesn't open one way, try another.
        """
        try:        
            self.wb = self.app.Workbooks(self.source_path)            
        except Exception as e:
            try:
                self.wb = self.app.Workbooks.Open(self.source_path)
            except Exception as e:
                print(e)
                self.wb = None   

    def get_column_after(self, column, offset):
        for item in self.ws.Range("{0}{1}:{0}{2}".format(column, offset, self.get_last_row_from_column(column))).Value:
            print(item[0])

    def get_last_row_from_column(self, column):
        return self.ws.Range("{0}{1}".format(column, self.ws.Rows.Count)).End(win32com.client.constants.xlUp).Row


def main():
    f = ExcelInstance()
    f.get_column_after("A", 3)

if __name__ == "__main__":
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM