简体   繁体   中英

Python xlwings excel length of table

I'm working on automating some of my work in Excel. A big part of what I'm trying to do is compare some data to determine if it needs to be added into some kind of system or not.

The point where I'm struggling currently is looking up the length of the row in an Excel sheet. The data that is supplied via that Excel sheet may very strongly in length and I think it's sloppy coding if I would let Python just grab all and everything in it.

I have looked around a bit and found some suggestions to use the Range().vertical , but it does not seem to be in xlwings anymore.

A workaround I found was reading the compleet sheet, looping it until I found a cell containint "None", then stopping the loop, but this still feels much "non-python-ish).

eg. for the data i'm using

    A     B
    1 data1  stuff9
    2 data9  stuff4
    3 data3  stuff3
    4 data4  stuff2
    5

What I'm trying to find out is how many rows with data does column A have. In this example I should find 4 (as elegant as possible)

Using the method current_region and size, current_Region gives me back "1", size gives me back "1048576"(i think the max of excel, so it just keeps counting ;)) and the same goes for the end-method.

I just installed xlwings and spent 5 minutes looking at the docs, and come up with two options for you:

import xlwings as xw
app = xw.apps[0]
book = app.books[0]
sheet = book.sheets[0]
rng = sheet.range('A1')

# This gives the last row in the TABLE'S current_region
# This will take additional columns in to consideration
rng.current_region.end('down').row

# This gives the last row in column A
rng.end('down').row

Based on your example data, both methods yield the result of 4 , but you should note the differences, for example if column B has more data in it, then the first method is not suitable for identifying the "last row" in column A, it will always return the last row of the entire current_region object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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