效果:通过excel来批量导入公司的员工信息。
import_user.bat
python manage.py import_user --path training\management\commands\namelist.xlsx
import_user.py
# 如何批量从Excel文件导入候选人数据(命令行工具)
# python manage.py import_candidates --path /path/to/your/file.csv
import csv
import imp
from django.core.management import BaseCommand
from training.models import EmployeeUser
from django.contrib.auth.models import User
from openpyxl import load_workbook
# run command to import candidates:
# python manage.py import_candidates --path /path/to/your/file.csv
class Command(BaseCommand):
help = '从一个CSV文件的内容中读取人员列表,导入到数据库中'
def add_arguments(self, parser):
parser.add_argument('--path', type=str)
def handle(self, *args, **kwargs):
path = kwargs['path']
wb = load_workbook(path)
sheet = wb.active
for i in range(2,sheet.max_row+1): # 第一行不读
username = sheet.cell(i,2).value
password = sheet.cell(i,3).value
department = sheet.cell(i,4).value
employeename = sheet.cell(i,5).value
employeeid = sheet.cell(i,6).value
title = sheet.cell(i,7).value
role = sheet.cell(i,8).value
user = User.objects.create_user(username = username,password = password)
euser = EmployeeUser.objects.create(user = user,
department = department,
employeename = employeename,
employeeid = employeeid,
title = title,
role = role)
print(user)
print(euser)
namelist.xlsx
models.py
class EmployeeUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,related_name='employeeuser')
department = models.CharField(blank=True, null=True,choices=DEPT_TYPE, max_length=100, verbose_name=u'部门')
employeename = models.CharField(max_length=135, blank=True, null=True,verbose_name=u'姓名')
employeeid = models.CharField(max_length=135, blank=True, null=True,verbose_name=u'工号')
title = models.CharField(blank=True, null=True,max_length=100, verbose_name=u'职务')
role = models.CharField(blank=True, null=True,max_length=100, choices=ROLE_TYPE,verbose_name=u'角色')
score_ci = models.IntegerField(blank=True, null=True, default=0, verbose_name=u'CI调整的积分')
score_total = models.IntegerField(blank=True, null=True, default=0, verbose_name=u'共获取的积分')
score_used = models.IntegerField(blank=True, null=True, default=0, verbose_name=u'已使用的积分')
score_left = models.IntegerField(blank=True, null=True, default=0, verbose_name=u'剩余积分')
class Meta:
verbose_name = u'员工和积分'
verbose_name_plural = u'员工和积分'
def __str__(self):
return self.user.username + "拓展信息"