top of page

Use Python's xlrd library to extract multiple columns or rows


Here's a quick demo of how to use Python to pull a designated range from a spreadsheet.

In this example I'm working with this spreadsheet:

Import the the xlrd library

>>> import xlrd

Set the location of the file you are analyzing: >>> loc = ("C:\FooFolder\Cities.xlsx")

Access the workbook:

>>> wb = xlrd.open_workbook(loc)

Designate the worksheet number you're reviewing:

>>> sheet = wb.sheet_by_index(0)

Get a column heading: >>> sheet.cell_value(0,0)

'City'

Get the total number of rows on the worksheet with data, and then print just the data in those rows from the first column

>>> for i in range(sheet.nrows): print(sheet.cell_value(i,0))

City New York Los Angeles Chicago Houston Philadelphia Phoenix Montreal Toronto Mexico City >>>

Varying the script this way, will get all of the column headings:

>>> for x in range(sheet.ncols): print(sheet.cell_value(0,x))

City State Country

Check out Geeks for Geeks for more excellent Python tips.


bottom of page