一个有趣的数据处理功能实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24192465/article/details/82222033

//批量更新 导入按钮
	import_BatchUpdate_btn : function(sta) {
		var formData = new FormData();
		var name = $("#update_students").val();
		formData.append("file", $("#update_students")[0].files[0]);
		formData.append("name", name);
		formData.append("schCode", schoolId);
		formData.append("content", content);
		if (name.substr(name.indexOf(".") + 1, name.length) != "xlsx" && name.substr(name.indexOf(".") + 1, name.length) != "xls") {
			Tomd.alert("错误提示", "请选择excel", "");
			return;
		}
		var url = '';
		if(sta == 7){
			url = '../sch/master/student/selectImport';
		}else{
			url = '../sch/master/student/batchUpdateStudents';
		}
		
		Tomd.wait('导入中...');
		$.ajax({
			url : url,
			type : 'POST',
			cache : false,
			data : formData,
			// 告诉jQuery不要去处理发送的数据  
			processData : false,
			// 告诉jQuery不要去设置Content-Type请求头  
			contentType : false,
			beforeSend : function() {
				//console.log("正在进行,请稍候");  
			},
			success : function(s) {
				Tomd.waitok();
				if (s.code == 0) {
					Men.close_window();
					Tomd.toast('right', '', "导入成功");
					$('#datatable_teacher').dataTable().fnReloadAjax();
				} else {
					$(".dropify-clear").trigger("click"); //上传区域清空
					var datas = s.data;
					$(".error").remove();
					$.each(datas, function(index, value) {
						var text = index + "、" + value;
						$("#error_info").append(`<label class="error col-4">${text}</label>`); //把错误信息显示在上传控件上方
					});
				}
			},
			error : function(e) {
				Tomd.waitok();
				Tomd.alert("失败提示", "导入失败", "");
			}
		});
	},
//批量更新
$("#student_import_BatchUpdate").on("change", function() {
	var sta = $(this).val();
	if($(this).val() == '7'){
		content = $("#student_import_BatchUpdate :selected").val();
		var title = '批量更新:' + $(this).find("option:selected").text();
		var html = `<div class="col-12 text-right" style="margin-bottom:.5rem"><button class="default_btn" onclick="updateSelectTemplate()">下载模板</button></div><div class="col-12"><div id="error_info"></div><input type="file" id="update_students" name="file" class="dropify-fr"
		data-default-file="" multiple="multiple" accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/></div>`;
		Men.new_window(title, html, '取消');
		$(".center_popup").addClass("wid50");
		$('.center_button_div').prepend(`<button class="default_btn edit_row_btn" onclick="student.import_BatchUpdate_btn('${sta}')">导入</button>`);
		//初始化上传控件
		Men.dropify();
		$(this).val(0);
	}else if ($(this).val() != '0') {
		content = $("#student_import_BatchUpdate :selected").val();
		var title = '批量更新:' + $(this).find("option:selected").text();
		var html = `<div class="col-12 text-right" style="margin-bottom:.5rem"><button class="default_btn" onclick="updateTemplate()">下载模板</button></div><div class="col-12"><div id="error_info"></div><input type="file" id="update_students" name="file" class="dropify-fr"
		data-default-file="" multiple="multiple" accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/></div>`;
		Men.new_window(title, html, '取消');
		$(".center_popup").addClass("wid50");
		$('.center_button_div').prepend(`<button class="default_btn edit_row_btn" onclick="student.import_BatchUpdate_btn('${sta}')">导入</button>`);
		//初始化上传控件
		Men.dropify();
		$(this).val(0);
	}
});

updateTemplate = function() {
	window.open('../template/批量更新学生模板.xlsx', '_blank');
}

updateSelectTemplate = function() {
	window.open('../template/批量更新学生选课班模板.xlsx', '_blank');
}
<button class="default_btn gray_btn" onclick="student.newly_open()">新增学生</button>
	&emsp; 批量更新:<select class="default_select"
		id="student_import_BatchUpdate">
		<option value="0">请选择</option>
		<option value="1">状态</option>
		<option value="2">借读</option>
		<option value="3">性别</option>
		<option value="4">是否特殊</option>
		<option value="5">学生来源</option>
		<option value="6">就读方式</option>
		<option value="7">选课班</option>
	</select>
@ResponseBody
	@PostMapping("/selectImport")
	public JSONObject selectImport(@RequestParam("file") MultipartFile file, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException{
		// 学校编号
		String schCode = request.getParameter("schCode");
		ReadSPExcel readSPExcel = new ReadSPExcel();
		String originalFilename = file.getOriginalFilename();// 原文件名字
		JSONObject param = new JSONObject();
		param.put("fileName", originalFilename);
		JSONObject returnObj = new JSONObject();
			List<StudentClazzImport> list;
			JSONArray studentClazzs = null ;
			try {
				InputStream is = file.getInputStream();// 获取输入流
				list = readSPExcel.readExcel(is,param);
				studentClazzs = getJSONArrayByList(list);
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("schCode", schCode);
				params.put("studentClazzs", studentClazzs);
				returnObj = studentService.selectImport(params);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return returnObj;
	}
	private int row;//数据行号
	private Long schCode;// 学校编号
	private Integer grade;// 年级
	private Long stuNo;// 校内学号
	private List<OptionClazz> clazzs;//选课班导入信息
	private String clzName;// 班级名称
	private Integer examCategory;// 考试类型(选课类型)
	private String subjectCode; // 编号
	private Long clzCode; // 编号
package com.moofen.cube.util;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.NumberToTextConverter;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.alibaba.fastjson.JSONObject;
import com.moofen.core.constant.ExcelConstant;
import com.moofen.core.entity.excel.imp.OptionClazz;
import com.moofen.core.entity.excel.imp.StudentClazzImport;

public class ReadSPExcel {

	public List<StudentClazzImport> readExcel(InputStream is, JSONObject param)
			throws Exception, IOException, FileUploadException {
		String fName = param.getString("fileName");
		String fileName[] = fName.split("\\.");
		String suffix = fileName[fileName.length - 1].toLowerCase();
		List<StudentClazzImport> stuList = new ArrayList<StudentClazzImport>();
		if (suffix.endsWith(ExcelConstant.FILE_UPLOAD_LIMIT_XLS)) {
			stuList = readXls(is);
		} else if (suffix.endsWith(ExcelConstant.FILE_UPLOAD_LIMIT_XLSX)) {
			stuList = readXlsx(is);
		}

		return stuList;
	}

	HSSFWorkbook hssfWorkbook = null;


	public List<StudentClazzImport> readXls(InputStream is)
			throws Exception, IOException {
		hssfWorkbook = new HSSFWorkbook(is);
		try {
			List<StudentClazzImport> stuList = new ArrayList<StudentClazzImport>();
			HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
			// int coloumNum = hssfSheet.getRow(0).getPhysicalNumberOfCells();
			for (int rowNum = 2; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
				StudentClazzImport stuCls = new StudentClazzImport();
				List<OptionClazz> clazzs = new ArrayList<OptionClazz>();
				HSSFRow hssfRow = hssfSheet.getRow(rowNum);
				int flag = 0;
				if (hssfRow != null) {
					HSSFCell cellV = hssfRow.getCell(0);
					if (cellV == null || StringUtils.isBlank(getValue(cellV))) {
						flag = 1;
						continue;
					}

					stuCls.setRow(rowNum + 1);
					stuCls.setSchCode(Long.valueOf(getValue(hssfRow.getCell(0))));
					stuCls.setGrade(Integer.valueOf(getValue(hssfRow.getCell(1))));
					stuCls.setStuNo(Long.valueOf(getValue(hssfRow.getCell(3))));
					int xk = 1;
					for (int c = 4; c < 29; c++) {
						if (hssfRow.getCell(c) != null && !StringUtils.isBlank(getValue(hssfRow.getCell(c)))) {
							OptionClazz sub = new OptionClazz();
							if (getValue(hssfRow.getCell(c)).equals("必考")) {
								sub.setExamCategory(0);
							} else if (getValue(hssfRow.getCell(c)).equals("选考")) {
								sub.setExamCategory(1);
							} else if (getValue(hssfRow.getCell(c)).equals("学考")) {
								sub.setExamCategory(2);
							}
							++c;
							sub.setClzName(getValue(hssfRow.getCell(c)));
							if (xk < 10) {
								sub.setSubjectCode(xk + "");
							} else if (xk == 10) {
								sub.setSubjectCode("A");
							} else if (xk == 11) {
								sub.setSubjectCode("B");
							} else if (xk == 12) {
								sub.setSubjectCode("C");
							} else if (xk == 13) {
								sub.setSubjectCode("D");
							}
							xk++;
							clazzs.add(sub);
						} else {
							++c;
							xk++;
						}
					}
					if (flag == 0) {
						stuCls.setClazzs(clazzs);
						stuList.add(stuCls);
					}
				}
			}
			return stuList;
		} catch (Exception e) {
			throw e;
		} finally {
			is.close();
		}
	}

	XSSFWorkbook xssfWorkbook = null;

	public List<StudentClazzImport> readXlsx(InputStream is)
			throws Exception, IOException {
		List<StudentClazzImport> stuList = new ArrayList<StudentClazzImport>();
		try {
			xssfWorkbook = new XSSFWorkbook(is);
			XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
			// JSONArray list = new JSONArray();
			// int coloumNum = xssfSheet.getRow(0).getPhysicalNumberOfCells();
			for (int rowNum = 2; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {

				StudentClazzImport stuCls = new StudentClazzImport();
				List<OptionClazz> clazzs = new ArrayList<OptionClazz>();
				XSSFRow xssfRow = xssfSheet.getRow(rowNum);

				int flag = 0;
				if (xssfRow != null) {

					XSSFCell cellV = xssfRow.getCell(0);
					if (cellV == null || StringUtils.isBlank(getValue(cellV))) {
						flag = 1;
						continue;
					}

					stuCls.setRow(rowNum + 1);
					stuCls.setSchCode(Long.valueOf(getValue(xssfRow.getCell(0))));
					stuCls.setGrade(Integer.valueOf(getValue(xssfRow.getCell(1))));
					stuCls.setStuNo(Long.valueOf(getValue(xssfRow.getCell(3))));
					int xk = 1;
					for (int c = 4; c < 29; c++) {
						if (xssfRow.getCell(c) != null && !StringUtils.isBlank(getValue(xssfRow.getCell(c)))) {
							OptionClazz sub = new OptionClazz();
							if (getValue(xssfRow.getCell(c)).equals("必考")) {
								sub.setExamCategory(0);
							} else if (getValue(xssfRow.getCell(c)).equals("选考")) {
								sub.setExamCategory(1);
							} else if (getValue(xssfRow.getCell(c)).equals("学考")) {
								sub.setExamCategory(2);
							}
							++c;
							sub.setClzName(getValue(xssfRow.getCell(c)));
							if (xk < 10) {
								sub.setSubjectCode(xk + "");
							} else if (xk == 10) {
								sub.setSubjectCode("A");
							} else if (xk == 11) {
								sub.setSubjectCode("B");
							} else if (xk == 12) {
								sub.setSubjectCode("C");
							} else if (xk == 13) {
								sub.setSubjectCode("D");
							}
							xk++;
							clazzs.add(sub);
						} else {
							++c;
							xk++;
						}
					}
					if (flag == 0) {
						stuCls.setClazzs(clazzs);
						stuList.add(stuCls);
					}
				}
			}
			return stuList;
		} catch (Exception e) {
			throw e;
		} finally {
			is.close();
		}
	}

	@SuppressWarnings("deprecation")
	protected String getValue(Cell c) {

		String r = null;
		if (c == null) {
			r = "";
		}
		switch (c.getCellType()) {
		case Cell.CELL_TYPE_BLANK:// 为 空值3
			r = "";
			break;
		case Cell.CELL_TYPE_BOOLEAN:// boolean型4
			r = c.getBooleanCellValue() + "";
			break;
		case Cell.CELL_TYPE_ERROR:// 错误 5
			r = "";
			break;
		case Cell.CELL_TYPE_FORMULA:// 公式型 2
			Workbook wb = c.getSheet().getWorkbook();// 取得workbook
			CreationHelper helper = wb.getCreationHelper();// 取得wb的帮助
			FormulaEvaluator ev = helper.createFormulaEvaluator();// 取得helper的公式计算方法
			r = getValue(ev.evaluateInCell(c));// 调用自身方法,括号里取得cellValue
			break;
		case Cell.CELL_TYPE_NUMERIC:// 数值型 0
			if (DateUtil.isCellDateFormatted(c)) {// 如果是excel日期格式
				SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 规定日期格式
				Date d = c.getDateCellValue();// 取得日期
				r = s.format(d);// 转换日期格式
			} else {
				// r = getNumber( String.valueOf(c.getNumericCellValue())
				// );//数值的话,转换为String
				r = NumberToTextConverter.toText(c.getNumericCellValue());
			}
			break;
		case Cell.CELL_TYPE_STRING:// 字符串型 1
			r = c.getRichStringCellValue().toString();// 推荐使用getRichStringCellValue();
														// getStringCellValue()为老方法
			break;
		default:
			r = "";
		}
		return r.trim();
	}

}
	@PostMapping("/import")
	public BaseResult createStudentsImport(@RequestParam(name = "schCode")String schCode,@RequestParam(name = "studentClazzs") String studentClazzs) {
		studentClazzs=MoofenUtil.formatJson(studentClazzs);
		List<StudentClazzImport> studentClazzImportList= JSON.parseArray(studentClazzs, StudentClazzImport.class);
		return studentClazzSPService.createStudentsImport(new Long(schCode),studentClazzImportList);
	}
	private String stuClzCode;// 学生班级,系统生成,唯一编号
	private Long schCode;// 学校编号
	private Student student;// 学生
	private Clazz clazz;// 班级
	private Integer examCategory;// 考试类型(选课类型)
	private List<com.moofen.core.entity.sys.base.Subject> subjects;// 学科
	private String status;// 状态,E-启用 D-停用
	private String schStuCode;// 学校学生编号,系统生成,唯一编号
	private Long schCode; // 学校编号
	private com.moofen.core.entity.biz.sch.Student student;// 学生
	private Clazz adminClazz;// 行政班编号,对应smi_clazz的clzCode
	private Long stuNo;// 校内学号,两位入学年份+五位流水号或者学校自定义,校内唯一
	private String stuAlias;// 学生别名
	private Integer isTransient;// 是否借读,1-是借读生 0-不是借读生
	private Integer stuSource;// 学生来源,1-应届 2-往届
	private Integer stuWay;// 就读方式,1-走读 2-住校
	private Integer isSpecial;// 特殊学生,1-是 0-否
	private String remarks;// 备注
	private List<StudentTag> stuTags;// 学生标签
	private String examNo;// 考号,每次考试可能不同,下次考试的考试号码,默认是学号
	private String status;// 状态,E-启用 D-停用
	private String reason;// 停用原因,转学、休学、留级
	private Long clzCode;// 班级编号,学校编号+学届编号+四位流水号
	private Long schCode;// 学校编号
	private Grade grade; // 所在年级
	private Integer yearIn;// 学级
	private Integer clzSerial;// 班级序号
	private String clzProperty;// 班级属性,10-行政班 20-选课班
	private ClazzType clzType;// 班级类型
	private String clzName;// 班级名称
	private String clzAlias;// 班级别名
	private List<ClazzTag> clzTags;// 班级标签
public class Subject extends CodeNameEntity {

	private static final long serialVersionUID = 4907521726095661522L;

	public Subject() {
		super();
	}

	public Subject(String code, String name) {
		super(code, name);
	}

}
/**
 *  Copyright (C) 2017 上海牧分信息科技有限公司版权所有
 *  
 *  项目: Moofen MDE Project 
 *  文件:com.moofen.mde.sch.master.impl.StudentSPServiceImpl.java
 *  描述:学校主数据-学生的基础数据管理业务逻辑特殊服务
 *  作者:shenfeng
 *  日期:2018年06月12日
 * 
 */
package com.moofen.mde.sch.master.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.moofen.core.entity.excel.imp.OptionClazz;
import com.moofen.core.entity.excel.imp.StudentClazzImport;
import com.moofen.core.entity.sch.master.Clazz;
import com.moofen.core.entity.sch.master.Grade;
import com.moofen.core.entity.sch.master.Student;
import com.moofen.core.entity.sch.master.StudentClazz;
import com.moofen.core.entity.sys.base.Subject;
import com.moofen.core.mvc.service.impl.BaseServiceImpl;
import com.moofen.core.mvc.view.BaseResult;
import com.moofen.core.mvc.view.ErrorBuilder;
import com.moofen.mde.sch.master.StudentClazzSPService;

@Service("mde.sch.master.StudentClazzSPService")
public class StudentClazzSPServiceImpl extends BaseServiceImpl implements StudentClazzSPService {

	@Resource(name = "rdas.sch.master.StudentService")
	private com.moofen.rdas.sch.master.StudentService studentService;
	@Resource(name = "rdas.sch.master.StudentClazzService")
	private com.moofen.rdas.sch.master.StudentClazzService studentClazzService;
	@Resource(name = "rdas.sch.master.ClazzService")
	private com.moofen.rdas.sch.master.ClazzService clazzService;
	@Resource(name = "mde.sch.master.StudentClazzService")
	private com.moofen.mde.sch.master.StudentClazzService mdeStudentClazzService;
	@Resource(name = "rdas.sch.master.SubjectService")
	private com.moofen.rdas.sch.master.SubjectService subjectService;
	@Resource(name = "rdas.sch.master.GradeService")
	private com.moofen.rdas.sch.master.GradeService gradeService;

	/**
	 * 批量导入数据
	 * 
	 * @param String
	 *            schCode 学校编码
	 * @param List<StudentClazzImport>
	 *            studentImportList 导入数据列表
	 * @return BaseResult 是否新增成功
	 */
	@SuppressWarnings("unchecked")
	@Override
	public BaseResult createStudentsImport(Long schCode, List<StudentClazzImport> studentClazzImportList) {
		BaseResult result=new BaseResult();
			if (studentClazzImportList == null || studentClazzImportList.size() == 0)
			return new BaseResult();// 没有要新增的数据
		//整理成StudentClazz格式,不过subject没合并,一个科目一条记录
		result=genStudentClazzList(schCode,studentClazzImportList);
		if(!result.isSuccess())return result;//有错误数据		
		List<StudentClazz> studentClazzs=(List<StudentClazz>)result.getData();
		//按学生+班级整理成可以保存的格式
		List<StudentClazz> dealedStudentClazzs=deal(schCode,studentClazzs);
		//保存整理好的学生班级数据
		mdeStudentClazzService.createStudentClazzs(dealedStudentClazzs);
		return new BaseResult();//返回导入成功
	}

	//按学生+班级整理成可以保存的格式
	private List<StudentClazz> deal(Long schCode, List<StudentClazz> studentClazzs) {
		//按学生+班级整理成map
		HashMap<String,List<StudentClazz>> studentClazzsMap=dealMap(studentClazzs);
		List<StudentClazz> result=new ArrayList<>();//处理结果
		for(String key:studentClazzsMap.keySet()){//map里一条记录就是要合并成一条的学生班级数据
			List<StudentClazz> aStudentClazzList=studentClazzsMap.get(key);//要处理成一条学生班级数据
			StudentClazz dealedStudentClazz=new StudentClazz();//一条处理处理好的学生班级数据
			List<com.moofen.core.entity.sys.base.Subject> subjects=new ArrayList<>();// 合并的学科
			dealedStudentClazz.setSubjects(subjects);
			for (StudentClazz studentClazz : aStudentClazzList) {
				dealedStudentClazz.setSchCode(schCode);// 学校编号
				dealedStudentClazz.setStudent(studentClazz.getStudent());// 学生
				dealedStudentClazz.setClazz(studentClazz.getClazz());// 班级
				dealedStudentClazz.setExamCategory(studentClazz.getExamCategory());// 考试类型(选课类型)
				dealedStudentClazz.getSubjects().addAll(studentClazz.getSubjects());//合并的学科
			}
			result.add(dealedStudentClazz);//处理好放入返回结果
		}

		return result;
	}

	//按学生+班级整理成map
	private HashMap<String, List<StudentClazz>> dealMap(List<StudentClazz> studentClazzs) {
		HashMap<String, List<StudentClazz>> studentClazzsMap=new HashMap<>();//key:学生Code+班级Code
		for (StudentClazz studentClazz : studentClazzs) {
			String key=studentClazz.getStudent().getSchStuCode()+""+studentClazz.getClazz().getClzCode();
			List<StudentClazz> value=new ArrayList<>();
			if(studentClazzsMap.containsKey(key)){//map有数据就在原有数据里加本条学生班级
				value=studentClazzsMap.get(key);
			}
			value.add(studentClazz);
			studentClazzsMap.put(key, value);//加入map
		}
		return studentClazzsMap;
	}

	//整理成StudentClazz格式,不过subject没合并,一个科目一条记录
	private BaseResult genStudentClazzList(Long schCode, List<StudentClazzImport> studentClazzImportList) {
		List<Grade> grades=gradeService.findGrades(schCode, null, null, null, null);
		List<Student> students = studentService.findStudents(schCode, null, null, null, null);
		List<StudentClazz> stuClz = studentClazzService.findStudentClazzs(schCode, null, null, null, null);
		HashMap<String, String> gradeMap=genGradeMap(grades);
		HashMap<String, String> stuMap=genStuMap(students);
		HashMap<String, String> stuClzMap=stuClzMap(stuClz);
		List<String> errorStrs = new ArrayList<>();//报错信息
		List<StudentClazz> studentClazzs=new ArrayList<>();//处理结果
		for (StudentClazzImport studentClazzImport : studentClazzImportList) {
			
			Long schcode = studentClazzImport.getSchCode();
			if(!schcode.equals(schCode)){
				//学校数据
				String error = "Excel第"+studentClazzImport.getRow()+"行学校编号["+schcode+"]与当前选择学校的编号["+schCode+"]不匹配!";
				errorStrs.add(error);
				continue;
			}
			String stuno=studentClazzImport.getStuNo().toString();
			if(!stuMap.containsKey(stuno)){
				//学生学号数据有错
				String error = ErrorBuilder.buildError(ErrorBuilder.IMPORT_DATA_NOT_FOUND_ERROR,schCode,"第"+studentClazzImport.getRow()+"行学生学号["+stuno+"]").getMessage();
				errorStrs.add(error);
				continue;
			}
			
			String grade=studentClazzImport.getGrade().toString();
			if(!gradeMap.containsKey(grade)){
				//年级数据有错
				String error = ErrorBuilder.buildError(ErrorBuilder.IMPORT_DATA_NOT_FOUND_ERROR,schCode,"第"+studentClazzImport.getRow()+"行年级["+grade+"]").getMessage();
				errorStrs.add(error);
				continue;
			}
			
			for (OptionClazz optionClazz : studentClazzImport.getClazzs()) {
				StudentClazz studentClazz=new StudentClazz();
				Long grdCode=null;
				grdCode=new Long(gradeMap.get(grade));
				Clazz clazz=getClazzBy(schCode, grdCode, optionClazz.getClzName());
				
				if(clazz==null){
					//班级数据有错
					String error = ErrorBuilder.buildError(ErrorBuilder.IMPORT_DATA_NOT_FOUND_ERROR,schCode,"第"+studentClazzImport.getRow()+"行班级["+optionClazz.getClzName()+"]").getMessage();
					errorStrs.add(error);
					continue;
				}
				
				if((clazz.getClzProperty()).equals("10")){
					//学校数据
					String error = "Excel中的班级不能有行政班,第"+studentClazzImport.getRow()+"行中班级["+clazz.getClzName()+"]是行政班!";
					errorStrs.add(error);
					continue;
				}
				Map<String, Object> conds = new HashMap<String, Object>();
				conds.put("clzCode", clazz.getClzCode().toString());
				List<com.moofen.core.entity.sch.master.Subject> subj = subjectService.findSubjects(schcode, conds, null, null, null);
				com.moofen.core.entity.sch.master.Subject subje = subj.get(0);
				List<com.moofen.core.entity.sys.base.Subject> subs = subje.getSubjects();
				HashMap<String, String> clzSubMap= ClzSubMap(subs);
				if(!clzSubMap.containsKey(optionClazz.getSubjectCode())){
					//学科和班级不对应
					String error = "Excel第"+studentClazzImport.getRow()+"行班级["+optionClazz.getClzName()+"]没有相对应的学科,请检查系统班级详细数据!";
					errorStrs.add(error);
					continue;
				}
				
			
//				if(clzHaveStudents(clazz)){
//					//班级数据有错
//					String error = ErrorBuilder.buildError(ErrorBuilder.IMPORT_DATA_EXISTED_ERROR,"第"+studentClazzImport.getRow()+"行数据的班级["+clazz.getClzName()+"]").getMessage();
//					errorStrs.add(error);
//					continue;
//				}
				studentClazz.setClazz(clazz);// 班级
				studentClazz.setSchCode(schCode);// 学校编号
				Student student=new Student();
				Long stuNo=studentClazzImport.getStuNo();
				student.setSchStuCode(schCode + "" + stuNo);
				
				
				if(stuClzMap.containsKey(student.getSchStuCode()+""+clazz.getClzCode())){
					//学生班级编号
					String error = "第"+studentClazzImport.getRow()+"行数据的学生班级["+clazz.getClzName()+"]已存在该学生,不能重复导入!";
					errorStrs.add(error);
					continue;
				}
				
				studentClazz.setStudent(student);// 学生
				studentClazz.setExamCategory(optionClazz.getExamCategory());// 考试类型(选课类型)
				List<com.moofen.core.entity.sys.base.Subject> subjects=new ArrayList<>();// 学科
				com.moofen.core.entity.sys.base.Subject subject=new com.moofen.core.entity.sys.base.Subject();
				subject.setCode(optionClazz.getSubjectCode());
				subjects.add(subject);
				studentClazz.setSubjects(subjects);
				studentClazzs.add(studentClazz);//加入处理结果
			}
		}
		if (errorStrs.size() == 0) {//没有错就返回StudentClazz列表
			BaseResult result =new BaseResult();
			result.setData(studentClazzs);
			return result;
		} else {//有错就返回错误信息列表
			BaseResult result = ErrorBuilder.buildError(ErrorBuilder.IMPORT_DATA_ERROR);
			result.setData(errorStrs);
			return result;
		}
	}
	//检查班级是否有学生数据
//	private boolean clzHaveStudents(Clazz clazz) {
//		Map<String, Object> conds=new HashMap<>();
//		conds.put("clzCode", clazz.getClzCode());
//		int num=mdeStudentClazzService.count(clazz.getSchCode(), conds);
//		return num>0;
//	}

	// 检查导入数据数据
	private Clazz getClazzBy(Long schCode, Long grdCode, String clzName) {
		// 查询对应的行政班
		Map<String, Object> conds = new HashMap<>();
		conds.put("grdCode", grdCode);
		conds.put("clzName.kd", clzName);
		List<Clazz> smiClazzs = clazzService.findClazzs(schCode, conds, null, null, null);
		if (smiClazzs == null || smiClazzs.size() == 0)return null;
		Clazz clazz = smiClazzs.get(0);// 对应的班级
		
		return clazz;
	}

	//整理成年级对应年级code的map
	private HashMap<String, String> genGradeMap(List<Grade> grades) {
		HashMap<String, String> codeMap=new HashMap<>();
		for (Grade grade : grades) {
			codeMap.put(grade.getGrade().toString(), grade.getGrdCode().toString());
		}
		return codeMap;
	}
	
	//整理成学号对应学号的map
	private HashMap<String, String> genStuMap(List<Student> students) {
		HashMap<String, String> codeMap=new HashMap<>();
		for (Student student : students) {
			codeMap.put(student.getStuNo().toString(), student.getStuNo().toString());
		}
		return codeMap;
	}
	
	//整理成学生班级对应学生班级的map
	private HashMap<String, String> stuClzMap(List<StudentClazz> stuClzs) {
		HashMap<String, String> codeMap=new HashMap<>();
		for (StudentClazz stuClz : stuClzs) {
			codeMap.put(stuClz.getStuClzCode().toString(), stuClz.getStuClzCode().toString());
		}
		return codeMap;
	}
	
	
	//整理成学科code对应学科code的map
	private HashMap<String, String> ClzSubMap(List<com.moofen.core.entity.sys.base.Subject> subs) {
		HashMap<String, String> codeMap=new HashMap<>();
		for (Subject sub : subs) {
			codeMap.put(sub.getCode().toString(), sub.getCode().toString());
		}
		return codeMap;
	}

}
@Override
	public void createStudentClazzs(List<StudentClazz> studentClazzList) {
		List<Document> documentList = new ArrayList<Document>();
		for (StudentClazz studentClazz : studentClazzList){
			studentClazz.setDefault();
			Document document = new Document(getIndex(studentClazz.getSchCode()), getType(), studentClazz.getStuClzCode().toString(), studentClazz.toDocument());;
			documentList.add(document);
		}
		eao.create(documentList);
	}

猜你喜欢

转载自blog.csdn.net/qq_24192465/article/details/82222033