How to use Python to read one column from Excel file?

Viewed 85159

I want to read the data in one column in excel, here is my code:

import xlrd

file_location = "location/file_name.xlsx"

workbook = xlrd.open_workbook(file_location)

sheet = workbook.sheet_by_name('sheet')

x = []

for cell in sheet.col[9]:

    if isinstance(cell, float):

        x.append(cell)

print(x)

It is wrong because there is no method in sheet called col[col.num], but I just want to extract the data from column 8 (column H), what can I do?

5 Answers

XLRD is good, but for this case you might find Pandas good because it has routines to select columns by using an operator '[ ]'

Complete Working code for your context would be

import pandas as pd
file_location = "file_name.xlsx"
sheet = pd.read_excel(file_location)
print(sheet['Sl'])

Output 1 - For column 'Sl'

0    1
1    2
2    3
Name: Sl, dtype: int64

Output 2 - For column 'Name'

print(sheet['Name'])
0      John
1      Mark
2    Albert
Name: Name, dtype: object

Reference: file_name.xlsx data

Sl  Name
1   John
2   Mark
3   Albert
Related