django读取excel表格并引用自定义函数,然后插入mysql数据库库

django读取excel表格并引用自定义函数 , 然后插入mysql数据库库

view.py

# -*- coding: utf-8 -*-    
# 上一句话是要识别中文
from __future__ import unicode_literals

from django.shortcuts import render
from cmdb import models
from django.shortcuts import HttpResponse
from django.http import JsonResponse
import json
from django.core import serializers
# Create your views here.
from django.views.decorators.cache import cache_page
# 引入自定义模块
from cmdb.myfunction import to_mysql
# 导入excel 需要的包 需要用pip安装
# pip install xlrd 
import xlrd
import uuid
import random

@cache_page(60 * 15)  # 秒数,这里指缓存 15 分钟,不直接写900是为了提高可读性 这要提高加载速度
# 读取excel表格
def excel_import(request):
    file_excel = 'C:/Users/Administrator/Desktop/data.xls'
    col_name_index = 0
    by_name = u'Sheet1'
    data = xlrd.open_workbook(file_excel)
    table = data.sheet_by_name(by_name)
    n_rows = table.nrows  # 行数
    row_dict = {}
    for row_num in range(1, n_rows):
        row = table.row_values(row_num)
        # seq = [row[0], row[1], row[2], row[3]]
        seq = {'user': row[0], 'pwd': row[1], 'ages': row[2], 'sex': row[3]}
        row_dict[row_num] = seq
    da = {
        'code': '200',
        'msg': '成功',
        'data': row_dict
    }
    # 调用方法 ---自定义模板函数 这里必须要return
    return to_mysql(da)

自定义函数的文件 myfunction.py

from django.http import JsonResponse
def to_mysql(data):
    return JsonResponse(data, content_type='application/json')

定义models.py

from __future__ import unicode_literals

from django.db import models

# Create your models here.
class UserInfo(models.Model):
    user = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)
    ages = models.CharField(max_length=32)
    sex = models.CharField(max_length=10, default='1')

运行命令,映射到数据库

python manage.py makemigrations
python manage.py migrate

修改自定义函数的文件 myfunction.py

from cmdb import models
from django.core import serializers
from django.shortcuts import HttpResponse
from django.http import JsonResponse
def to_mysql(data):
    a = data['data']
    for key in a:
        arrs = a[key]
        models.UserInfo.objects.create(user=arrs['user'], pwd=arrs['pwd'], ages=arrs['ages'], sex=arrs['sex'])

    user_list = models.UserInfo.objects.all()
    ajax_testvalue = serializers.serialize("json", user_list)

    return HttpResponse(ajax_testvalue, content_type='application/json')

至此插入成功,

有表达不清楚的地方可留言

你可能感兴趣的:(网络学习日志,python)