Vesper
Vesper

Reputation: 845

how to get the last column using xlwings?

So I have an excel file that contains data in this format: enter image description here I want to read this data using xlwings and I want this to be dynamic that means if I add the data in the or middle of this then it should be able to do this. I have tried this so far but it is not working properly:

import xlwings as xw
app = xw.App(visible=False)
    try:
        wb1 = app.books.open(commonInputs)
        sheet = wb2.sheets['Regional Transmission Links']
        lastCell = generatorSheet.range('A1').end('right').last_cell.column
        name = sheet.range('C5:L'+str(lastCell)).value
    except Exception as e:
        logging.exception("Something awful happened!")
        print(e)
    finally:
        app.quit()
        app.kill()

Can someone please help ?

Upvotes: 2

Views: 4875

Answers (1)

mouwsy
mouwsy

Reputation: 1933

I hope I understood your question right: How to get the last column of your table using xlwings? You can get it as follows.

Last column as integer

sheet["A1"].expand("right").last_cell.column

.column gives you the column of the cell as a number (1-indexed), e.g. for column C it gives you 3.

Last column as letter

sheet["A1"].expand("right").last_cell.address.split("$")[1]

.address gives you the range reference with two dollar signs, e.g. $C$1, and the .split part outputs only the letter, e.g. C.


As a side note, instand of sheet["A1"].expand("right"), it would be also possible to use sheet["A1"].expand() or sheet.used_range.

Upvotes: 8

Related Questions