How to import an xls file into Python?

7

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.

    
asked by anonymous 08.04.2015 / 00:06

2 answers

4

You'll need external libraries like xlrd to do this, take a look at www.python-excel.org

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 .

    
08.04.2015 / 15:32
0

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):
        linhas.append(
            {
                '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.

    
04.11.2016 / 02:04