How to import an xls file into Python?

Posted on

Question :

I’m starting my studies in Python and would like to import a database that is in .xls to Python. Could someone help me?

NOTE: Python version 3.4.3.


Answer :

You’ll need external libraries like xlrd to do this, take a look at

In any case I suggest saving the file as csv from excel and using the python csv module, it will save you a lot of time and headache

Example that I copied in the face of the site official :

import csv
with open('eggs.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                        quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

See more examples here .


A real example using xlrd:

import xlrd

def xls_parser(arquivo):
    tabela = xlrd.open_workbook(arquivo).sheet_by_index(0)
    qtd_linhas = tabela.nrows
    linhas = []
    for i in range(1, qtd_linhas):
                'linha': i + 1,
                'valor_coluna_1': tabela.row(i)[0].value,
                'valor_coluna_2': tabela.row(i)[1].value,
    return linhas

In the above example, the function receives the file path and places the cursor at the beginning of the file. From there it fetches the total lines of the file.

Having total rows, it makes a for using range and transfers that information to a list of dictionaries, making manipulation easier.

The script also stores the line in which the XLS content was taken from the dictionaries. But you can remove that part if that information is not relevant.


Leave a Reply

Your email address will not be published. Required fields are marked *