3Django快速开发-将excel表格数据写入到数据库功能的实现

1创建目录文件(interview/management/commands/import_candidates.py):

import csv
from django.core.management import BaseCommand

class Command(BaseCommand):
    help = '从一个csv文件的内容中读取候选人列表,导入到数据库中'
    #定义父类里的方法
    def add_arguments(self, parser):
        #使用长连接--path,输出类型是字符串
        parser.add_argument('--path',type=str)
    #定义父类里的方法
    def handle(self, *args, **options):
        #获取文件路径
        path = options['path']
        #rt只读模式下,python在读取文本时会自动把\r\n转换成\n
        with open(path,'rt',encoding='utf-8') as f:
            #读取excel的csv文件
            reader = csv.reader(f,dialect='excel')
            #遍历文件(默认按列进行遍历
            for row in reader:
                #打印文件第一列
                print(row[0])

2测试上面代码:

D:\PycharmProjects\meetingroom>python manage.py import_candidates --path C:/Users/66907/Pictures/test1227.csv

#运行结果:
刘倩
蒋欣
刘华
李小龙

3存库:

import csv
from django.core.management import BaseCommand
from interview.models import Candidate
class Command(BaseCommand):
    help = '从一个csv文件的内容中读取候选人列表,导入到数据库中'
    def add_arguments(self, parser):
        parser.add_argument('--path',type=str)
    def handle(self, *args, **options):
        path = options['path']
        with open(path,'rt',encoding='utf-8') as f:
            #指定分隔符为逗号
            reader = csv.reader(f,dialect='excel',delimiter=',')
            for row in reader:
                # print(row[0])
                # print(row[1])
                candidate = Candidate.objects.create(
                    username = row[0],
                    city=row[1],
                    phone=row[2],
                    bachelor_school=row[3],
                    major=row[4],
                    degree=row[5],
                    test_score_of_general_ability=row[6],
                    paper_score=row[7]
                )
                print(candidate)

4运行命令测试并数据库查看数据:

D:\PycharmProjects\meetingroom>python manage.py import_candidates --path C:/Users/66907/Pictures/test1227.csv
刘倩
蒋欣
刘华
李小龙

 

posted @ 2021-12-27 21:18  linuxTang  阅读(417)  评论(0)    收藏  举报