I am using python xlwings to read a column of data in Excel 2013. Column A
is populated with numbers. To import this column into a python list py_list
, I have the following code;
import xlwings as xw
wb = xw.Book('BookName.xlsm')
sht = xw.Book('SheetName')
py_list = sht.range('A2:A40').value
The above code works if the column data is populated at A2:A40
. However, the column data can keep growing. Data can grow and stretch to A2:A46
or A2:A80
. The last row is empty. It is not known at compile time how many rows of data is in this column.
How can I modify the code to detect the empty cell at the last row so that the range of data can be read by py_list
?
I am open to using other python libraries to read the Excel data besides xlwings. I am using python v3.6
I went through xlwings documentation to look for something, didn't find something like this, but you can always try and go around this:
or I don't know try this:
at line 2, at first I tried doing something like this:
another option:
I say this a lot about reading files in from csv or excel, but I would use
pandas
.an alternative would be to use a dynamic formula using soemthing like OFFSET in excel instead of
'A2:A40'
, or perhaps a named range?I know this is an old question, but you can also use
openpyxl
Notes:
Pandas is an awesome library, but installing it just to read an excel column into a list is an overkill IMHO.
xlrd is not maintained anymore. From the xlrd github page
I found this as the easiest way to create lists from the entire columns in excel and it only takes the populated excel cells. import pandas as pd import numpy as np
After much trial and error, I will answer my own question.
The key to this question is finding out the number of rows in column
A
.The number of rows can be found with this single line using xlwings below;
One needs to read the API documentation carefully to get the answer.
http://docs.xlwings.org/en/stable/api.html#xlwings.Range
Once the number of rows is found, it is easy to figure out the rest.