Reading Excel (xls) files

For a simple MS Excel file (file.xls) with two columns of data and the first row as headers…

Use xlrd package to read file:

import xlrd
wb = xlrd.open_workbook('file.xls')
sh = wb.sheet_by_index(0)
colA = sh.col_values(0) # Make column 1 into a Python list
colB = sh.col_values(1) # Make column 2 into a Python list
colA.pop(0) # Delete 1st row (header)
colB.pop(0) # Delete 1st row (header)
plot(colA,colB,'o')

Dependencies: xlrd

Note 1: You can import sheets by name (rather by than by_index)

wb.sheet_names() # Use this to query the sheet names
sh = wb.sheet_by_name(u'Sheet1') # Use this to load the desired sheet

Note 2: Method pop is an easy way to “pop” a element out of a list. See documentation

Useful Links:

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s