Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load data from an xlsx file using python

Tags:

python

xlsx

this is my xlsx file :

enter image description here

and i want to get change this data to a dict like this :

{
    0:{
       'a':1,
       'b':100,
       'c':2,
       'd':10
    },
    1:{
       'a':8,
       'b':480,
       'c':3,
       'd':14
    }
...
}

so did somebody know a python lib to do this , and start from the line 124, and end of the line 141 ,

thanks

like image 423
zjm1126 Avatar asked Apr 02 '11 03:04

zjm1126


1 Answers

Options with xlrd:

(1) Your xlsx file doesn't look very large; save it as xls.

(2) Use xlrd plus the bolt-on beta-test module xlsxrd (find my e-mail address and ask for it); the combination will read data from xls and xlsx files seamlessly (same APIs; it examines the file contents to determine whether it's xls, xlsx, or an imposter).

In either case, something like the (untested) code below should do what you want:

from xlrd import open_workbook
from xlsxrd import open_workbook
# Choose one of the above

# These could be function args in real live code
column_map = {
    # The numbers are zero-relative column indexes
    'a': 1,
    'b': 2,
    'c': 4,
    'd': 6,
    }
first_row_index = 124 - 1
last_row_index = 141 - 1
file_path = 'your_file.xls'

# The action starts here
book = open_workbook(file_path)
sheet = book.sheet_by_index(0) # first worksheet
key0 = 0
result = {}
for row_index in xrange(first_row_index, last_row_index + 1):
    d = {}
    for key1, column_index in column_map.iteritems():
        d[key1] = sheet.cell_value(row_index, column_index)
    result[key0] = d
    key0 += 1
like image 119
John Machin Avatar answered Nov 10 '22 18:11

John Machin