热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

javaexcel导入试题

javaexcel导入试题,Go语言社区,Golang程序员人脉社

js读取导入的名称到对应的位置显示

$(function() {
        $('#myFile').on('change', function() {
            var originName = $(this).val();
            var fileName = originName.substring(originName.lastIndexOf('\')+1);
            fileName = '' + fileName + '';
            $('#file-list').html(fileName);
        });
	});
	function importExcel() {
		var myFile = $("#myFile").val();
		if (myFile.length <= 0) {
			dialogFun("批量导入试题", "请选择导入内容", 0);
			return false;
		}
		$("#importP").submit();
	}

 html代码实现


后台代码实现

/**
	 * 批量导入试题
	 * /admin/quest/importExcel
	 * @param request
	 * @param file
	 * @return
	 */
	@RequestMapping("/quest/importExcel")
	public String importExcel(HttpServletRequest request, @RequestParam("myFile") MultipartFile file) {
		try {
			Long companyId = SingletonLoginUtils.getCurrentCompanyId(request);
			logger.info("myFile:" + file.getName());
			examQuestionService.updateImportQuestionExcel(file, companyId);
			request.setAttribute("msg", "操作成功");
		} catch (BaseException e) {
			logger.error("QuestionAction.importExcel", e);
			request.setAttribute("msg", e.getMessage());
			return msgError;
		} catch (RecordFormatException e) {
			logger.error("QuestionAction.importExcel", e);
			request.setAttribute("msg", "图片格式化失败,请勿导入图片");
			return msgError;
		}
		catch (Exception e) {
			logger.error("AdminQuestionAction.randomQuestion", e);
			request.setAttribute("msg", e.getMessage());
			return msgError;
		}
		return "/common/success";
	}

 方法实现

/**
	 * 批量导入试题
	 * @param file 		文件
	 * @param companyId	公司ID
	 * @return
	 * @throws Exception
	 */
	public String updateImportQuestionExcel(MultipartFile file, Long companyId) throws Exception {
		// 	     datalist拼装List deadliest,
		HSSFWorkbook wookbook = new HSSFWorkbook(file.getInputStream());
		HSSFSheet sheet = wookbook.getSheetAt(0);
		// 		指的行数,一共有多少行+
		int rows = sheet.getLastRowNum();
		Calendar calendar = Calendar.getInstance();

		List subjectR = nxbSubjectService.getSubjectListByType(SubjectType.EXAM.toString());
		for (int i = 1; i <= rows; i++) {
			// 读取左上端单元格
			HSSFRow row = sheet.getRow(i);
			// 行不为空
			if (row != null) {
				// 获取到Excel文件中的所有的列
				int maxcell = row.getLastCellNum();
				// **读取cell**
				String cOntent= getCellValue(row.getCell((short) 0));// 试题内容
				String subjectId = getCellValue(row.getCell((short) 1));// 专业ID
				String pointId = trimZero(getCellValue(row.getCell((short) 2)));// 考点
				String isAsr = getCellValue(row.getCell((short) 3));// 正确答案
				String type = getCellValue(row.getCell((short) 4));// 题型
				String level = trimZero(getCellValue(row.getCell((short) 5)));// 试题难度
				String analyze = getCellValue(row.getCell((short) 6));// 解析

				String optiOnA= getCellValue(row.getCell((short) 7));  // A
				String optiOnB= getCellValue(row.getCell((short) 8));  // B
				String optiOnC= getCellValue(row.getCell((short) 9));  // C
				String optiOnD= getCellValue(row.getCell((short) 10)); // D
				String optiOnE= getCellValue(row.getCell((short) 11)); // E
				String optiOnF= getCellValue(row.getCell((short) 12)); // F
				String optiOnG= getCellValue(row.getCell((short) 13)); // D

				if(StringUtils.isEmpty(content)&&
						StringUtils.isEmpty(subjectId)&&
						StringUtils.isEmpty(isAsr)&&
						StringUtils.isEmpty(type)&&
						StringUtils.isEmpty(level)&&
						StringUtils.isEmpty(analyze)){
					break;
				}


				// 试题内容,专业,正确答案,试题类型,试题难度
				if (StringUtils.isEmpty(content) || StringUtils.isEmpty(subjectId) || StringUtils.isEmpty(isAsr) || StringUtils.isEmpty(type) || StringUtils.isEmpty(level)) {
					throw new BaseException(
							"第" + i + "行,试题内容为<" + content + ">的那条数据数据不能为空(试题内容,专业,正确答案,试题类型,试题难度)");
				}
				logger.info("试题类型:" + type);
				switch (type) {
					case "单选":
						type = "1";
						break;
					case "多选":
						type = "2";
						break;
					case "判断":
						type = "3";
						break;
					case "不定项":
						type = "5";
						break;
					default:
						throw new BaseException("第" + i + "行,试题内容为<" + content + ">的那条数据试题类型不正确(试题类型只能输入单选,多选,判断,不定项)");
				}
				// 专业ID必须是大于0的正整数
				if (!StringUtils.isNumber(subjectId)||Long.parseLong(subjectId)<=0) {
					throw new BaseException("第" + i + "行,试题内容为<" + content + ">的那条数据专业ID必须是大于0的正整数");
				}
				//该 专业ID必须是该公司所有
				NxbQuerySubject nxbQuerySubject=new NxbQuerySubject();
				nxbQuerySubject.setCompanyId(companyId);
				nxbQuerySubject.setSubjectId(Long.parseLong(subjectId));
				List subjectList = nxbSubjectDao.getSubjectList(nxbQuerySubject);
				if (subjectList==null||subjectList.size()==0) {
					throw new BaseException("第" + i + "行,试题内容为<" + content + ">的那条数据专业ID必须是该分公司所拥有的");
				}

//				// 考点必须是大于0的正整数
//				if (!StringUtils.isNumber(pointId)||Long.parseLong(pointId)<=0) {
//					throw new BaseException("第" + i + "行,试题内容为<" + content + ">的那条数据考点ID必须是大于0的正整数");
//				}
				// 试题难度
				logger.info("试题难度:" + level);
				switch (level) {
					case "一级":
						level = "1";
						break;
					case "二级":
						level = "2";
						break;
					case "三级":
						level = "3";
						break;
					default:
						throw new BaseException("第" + i + "行,试题内容为<" + content + ">的那条数据的试题难度必须是一级、二级、三级其中的一个");
				}
				int typeInt = ConvertUtils.objectToInt(type);
				// 如果为判断题最多2个选项
				if (typeInt == 3) {
					if (StringUtils.isEmpty(optionA) || StringUtils.isEmpty(optionB)) {
						throw new BaseException("第" + i + "行,试题内容为<" + content + ">的那条数据为判断题,选项A或选项B不能为空");
					}
					if (StringUtils.isNotEmpty(optionD) || StringUtils.isNotEmpty(optionE)
							|| StringUtils.isNotEmpty(optionF) || StringUtils.isNotEmpty(optionG)) {
						throw new BaseException("第" + i + "行,试题内容为<" + content + ">的那条数据为判断题,选项D,E,F,G必须为空");
					}
				}
				// 如果不是判断题,选项必须大于等于4个小于等于7个选项
				if (typeInt != 3) {
					if (StringUtils.isEmpty(optionA) || StringUtils.isEmpty(optionB) ) {
						throw new BaseException("第" + i + "行,试题内容为<" + content + ">的那条数据为选择题,选项A,B不能为空");
					}
				}
				// 如果为多选题正确答案必须在两个以上
				if (typeInt == 2 && isAsr.trim().length() <2) {
					throw new BaseException("第" + i + "行,试题内容为<" + content + ">的那条数据的为多选题,正确答案必须在两个以上(例:AB)");
				}
				// 如果为单选题或者判断题答案只能有一个
				if (typeInt == 1 || typeInt == 3) {
					if (isAsr.trim().length() > 1) {
						throw new BaseException("第" + i + "行,试题内容为<" + content + ">的那条数据的正确答案只能有一个(例:A)");
					}
				}
				// 选项不能超过7个字符
				if (isAsr.trim().length() > 7) {
					throw new BaseException("第" + i + "行,试题内容为<" + content + ">的那条数据正确答案不能超过7个字符(例AB)");
				}
				// 验证正确答案不能输入其他字符
				char[] asr = isAsr.toString().trim().toCharArray();
				String asrStr = "";
				for (int y = 0; y 的那条数据正确答案输入字符格式不正确(例AB)");
					}
				}
				isAsr = asrStr.substring(0, asrStr.length() - 1);


				Question question = new Question();
				question.setStatus(1);
				// 试题类型
				int qstType = typeInt;
				question.setQstType(qstType);
				// 验证项目ID
				Long subjectIdLOng= Long.valueOf(subjectId.trim());
				for (int x = 0; x 的那条数据的专业id不匹配");
				}
				// 验证考点
				if(StringUtils.isNotEmpty(pointId)){
					Long pointIdLOng= Long.valueOf(pointId.trim());
					ExamPoint point = new ExamPoint();
					point.setSubjectId(subjectIdLong);
					point.setId(pointIdLong);
					List pointList = pointDao.getPointList(point);
					if (!pointList.isEmpty()) {
						question.setPointId(pointIdLong);
					}
				}

				//调整答案顺序
				if(typeInt==2){
					String[] chars = isAsr.split(",");
					Arrays.sort(chars);
					if(ObjectUtils.isNotNull(chars)&&chars.length>1){
						StringBuilder isAsrs=new StringBuilder();
						for (String s:chars){
							isAsrs.append(s);
							isAsrs.append(",");
						}
						isAsr=isAsrs.substring(0,isAsrs.length()-1);
					}
				}
				question.setLevel(ConvertUtils.objectToInt(level));
				question.setQstContent(content);
				question.setIsAsr(isAsr);
				question.setQstAnalyze(analyze);
				question.setAddTime(new Date());
				question.setAuthor("admin");
				question.setCompanyId(companyId);	// 公司ID
				questionDao.addOneQuestion(question);
				int AASC = 64;
				List str = new ArrayList();
				// 把选项的值放入list中
				str.add(optionA);
				str.add(optionB);
				str.add(optionC);
				str.add(optionD);
				str.add(optionE);
				str.add(optionF);
				str.add(optionG);

				List optiOnList= new ArrayList<>();

				for (int k = 0; k > map = new HashMap<>();
				map.put("optionList", optionList);
				optionDao.addOptionBatch(map);
			}
		}
		return null;
	}





/**
	 * 获得Hsscell内容
	 *
	 * @param cell
	 * @return
	 */
	public String getCellValue(HSSFCell cell) {
		String value = "";
		if (cell != null) {
			switch (cell.getCellType()) {
			case HSSFCell.CELL_TYPE_FORMULA:
				break;
			case HSSFCell.CELL_TYPE_NUMERIC:
				value = cell.getNumericCellValue() + "";
				break;
			case HSSFCell.CELL_TYPE_STRING:
				value = cell.getStringCellValue().trim();
				break;
			default:
				value = "";
				break;
			}
		}
		return value.trim();
	}

	String trimZero(String str) {
		if (StringUtils.isNotEmpty(str)) {
			return str.replace(".0", "");
		}
		return str;
	}

工具类


public abstract class ConvertUtils {
    private static final DecimalFormat simpleFormat = new DecimalFormat("####");

    public static final boolean objectToBoolean(Object o) {
        return o != null?Boolean.valueOf(o.toString()).booleanValue():false;
    }

    public static final int objectToInt(Object o) {
        if(o instanceof Number) {
            return ((Number)o).intValue();
        } else {
            try {
                if(o == null) {
                    return -1;
                } else {
                    BigDecimal bigDecimal = new BigDecimal(o.toString());
                    bigDecimal.intValue();
                    return bigDecimal.intValue();
                }
            } catch (Exception var2) {
                var2.printStackTrace();
                return -1;
            }
        }
    }
}

试题模板如下所示:

项目中所用的依赖为:


        
            poi
            poi-2.5.1-final
            20040804
        
        
        
            org.apache.ant
            ant
            1.9.3
        

数据库插入 


		INSERT INTO nxb_exam_options (
		
		) VALUES
		
			(#{item.id},#{item.qstId},#{item.optContent},
			#{item.optOrder}, #{item.optAnswer},#{item.addTime})
		
	

推荐阅读
  • 部分转载自:http:blog.csdn.netliujiuxiaoshitouarticledetails69920917头文件#include<assert.h& ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • 点此学习更多SQL相关函数与字符串处理函数mysql函数一、简明总结ASCII(char)        返回字符的ASCII码值BIT_LENGTH(str)      返回字 ... [详细]
  • 微软头条实习生分享深度学习自学指南
    本文介绍了一位微软头条实习生自学深度学习的经验分享,包括学习资源推荐、重要基础知识的学习要点等。作者强调了学好Python和数学基础的重要性,并提供了一些建议。 ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • 拥抱Android Design Support Library新变化(导航视图、悬浮ActionBar)
    转载请注明明桑AndroidAndroid5.0Loollipop作为Android最重要的版本之一,为我们带来了全新的界面风格和设计语言。看起来很受欢迎࿰ ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • SpringBoot整合SpringSecurity+JWT实现单点登录
    SpringBoot整合SpringSecurity+JWT实现单点登录,Go语言社区,Golang程序员人脉社 ... [详细]
  • 本文讨论了在使用Git进行版本控制时,如何提供类似CVS中自动增加版本号的功能。作者介绍了Git中的其他版本表示方式,如git describe命令,并提供了使用这些表示方式来确定文件更新情况的示例。此外,文章还介绍了启用$Id:$功能的方法,并讨论了一些开发者在使用Git时的需求和使用场景。 ... [详细]
  • TPL实现Task.WhileAll扩展方法
    文章翻译整理自NikolaMalovic两篇博文:Task.WhileAllAwaitabletaskprogressreporting当Task.WhenAll遇见 ... [详细]
  • SQL Server 2008 到底需要使用哪些端口?
    SQLServer2008到底需要使用哪些端口?-下面就来介绍下SQLServer2008中使用的端口有哪些:  首先,最常用最常见的就是1433端口。这个是数据库引擎的端口,如果 ... [详细]
  • 基于词向量计算文本相似度1.测试数据:链接:https:pan.baidu.coms1fXJjcujAmAwTfsuTg2CbWA提取码:f4vx2.实验代码:imp ... [详细]
  • Spring MVC定制用户登录注销实现示例
    这篇文章描述了如何实现对SpringMVCWeb应用程序的自定义用户访问(登录注销)。作为前提,建议读者阅读这篇文章,其中介 ... [详细]
  • 题目描述:一个DNA序列由ACGT四个字母的排列组合组成。G和C的比例(定义为GC-Ratio)是序列中G和C两个字母的总的出现次数除以总的字母数目(也就是序列长度)。在基因工程中,这个 ... [详细]
author-avatar
星仔star-powerbz
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有