Place data from a spreadsheet in Excel in the database

Asked

Viewed 692 times

0

The database here of the company generates a report in Excel, I need to save this data in a database, initially sqlite3, to be able to display this data in a Django template in the future.

Example of Exel:

Nome do profissional,"Situação atual","Endereco E_Mail","Site","Site 2","Nascimento",
ABDIAS VENCESLAU DA SILVA NETO,"Ativo","[email protected]","","","07/07/1977",

Each of these data would be stored in the respective Django model and in the database.

What would be the best way to do that? Please send suggestions!

1 answer

0


Try it this way

py.models

class Funcionario(models.Model):
    nome = models.CharField(max_length=255),
    situacao = models.BooleanField,
    email = models.CharField(max_length=255)
    site = models.CharField(max_length=255)
    site2 = models.CharField(max_length=255)
    nascimento = models.DateField()

services.py (or any other file)

class ImportToDatabase(object):

    @staticmethod
    def import_data():
        with open('relatorio.csv') as csvfile:
            reader = csv.reader(csvfile, delimiter=',')
            for row in reader:
                obj, created = Funcionario.objects.get_or_create(
                    nome=row[0],
                    situacao=row[1],
                    email=row[2],
                    site=row[3],
                    site2=row[4],
                    nascimento=row[5]
                )

py views.

ImportToDatabase.import_data()

If you want to use the Function object it is loaded in the obj variable To know if the record has been inserted or loaded, use the boolean variable "created".

  • You can explain the logic more or less ?

  • I created a Functio model to store the information I will receive from the .csv. file.In the example I inherited from model but if this object is not represented in the database, you can inherit from Object itself. I created the Importtodatabase class to handle data import. with works as a Try Finally, the open function comes from the csv package and takes as parameter the name of the file that is in the root of my project. The Reader stores the contents of the file, I do a for going through the lines. Obj, created is the return of get_or_create, and the past arguments are a map of the values.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.