pythoncoder
pythoncoder

Reputation: 675

How to read the excel column as list using python?

How to read the excel column as list using python?

Excel data: Input File(input.xlsx)

Column1      Column2  Column3  Column4 
one          two      three    four    
22/03/1997   six      7        eight   

code

book = xlrd.open_workbook("input.xlsx")
sheet = book.sheet_by_index(0)

col = []

for i in range(1,sheet.nrows):
  col.append(str(sheet.row_values(i)))

But my code will print in row wise but i want to read data in column wise

Expected Output:

[[Column1,one,22/03/1997],[Column2,two,six],[Column3,three,7,],[ Column4,four,eight]]

Upvotes: 0

Views: 260

Answers (2)

Alderven
Alderven

Reputation: 8260

You can use pandas:

import pandas as pd

df = pd.read_excel('file.xlsx', header=None)
result = [list(df[x].values) for x in df.columns.values]

Output:

[['Column1', 'one', '22/03/1997'], ['Column2', 'two', 'six'], ['Column3', 'three', 7], ['Column4', 'four', 'eight']]

Upvotes: 1

Bharath
Bharath

Reputation: 113

import xlrd
book = xlrd.open_workbook("input.xlsx")
sheet = book.sheet_by_index(0)
col = []
for i in range(0,sheet.ncols):
    col.append(str(sheet.col_values(i)))
print col

Upvotes: 0

Related Questions