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

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

html代码实现

<div class="am-u-sm-8 am-u-md-6"><div class="am-form-group am-form-file"><button class="am-btn am-btn-danger am-btn-sm" type="button"><i class="am-icon-cloud-upload"></i> 选择要上传的文件</button><input id="myFile" type="file" value="" accept=".xls" name="myFile"/></div><div id="file-list"></div>
</div>
<div class="am-hide-sm-only am-u-md-4"></div>
<form action="/admin/quest/importExcel" method="post" id="importP" enctype="multipart/form-data" class="am-form">
</form>

后台代码实现

/*** 批量导入试题* /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<String[]> deadliest,HSSFWorkbook wookbook = new HSSFWorkbook(file.getInputStream());HSSFSheet sheet = wookbook.getSheetAt(0);//         指的行数,一共有多少行+int rows = sheet.getLastRowNum();Calendar calendar = Calendar.getInstance();List<NxbSubject> 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));// 专业IDString 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));  // AString optionB = getCellValue(row.getCell((short) 8));  // BString optionC = getCellValue(row.getCell((short) 9));  // CString optionD = getCellValue(row.getCell((short) 10)); // DString optionE = getCellValue(row.getCell((short) 11)); // EString optionF = getCellValue(row.getCell((short) 12)); // FString optionG = getCellValue(row.getCell((short) 13)); // Dif(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<NxbSubject> 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 < asr.length; y++) {asrStr += asr[y] + ",";if ("ABCDEFG".indexOf(String.valueOf(asr[y])) == -1) {throw new BaseException("第" + i + "行,试题内容为<" + content + ">的那条数据正确答案输入字符格式不正确(例AB)");}}isAsr = asrStr.substring(0, asrStr.length() - 1);Question question = new Question();question.setStatus(1);// 试题类型int qstType = typeInt;question.setQstType(qstType);// 验证项目IDLong subjectIdLong = Long.valueOf(subjectId.trim());for (int x = 0; x < subjectR.size(); x++) {if (subjectR.get(x).getSubjectId().longValue() == subjectIdLong.longValue()) {question.setSubjectId(subjectIdLong);break;}}// 如果输入的专业不匹配if (question.getSubjectId() == null || question.getSubjectId().intValue() <= 0) {throw new BaseException("第" + i + "行,试题内容为<" + content + ">的那条数据的专业id不匹配");}// 验证考点if(StringUtils.isNotEmpty(pointId)){Long pointIdLong = Long.valueOf(pointId.trim());ExamPoint point = new ExamPoint();point.setSubjectId(subjectIdLong);point.setId(pointIdLong);List<ExamPoint> 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);  // 公司IDquestionDao.addOneQuestion(question);int AASC = 64;List<String> str = new ArrayList<String>();// 把选项的值放入list中str.add(optionA);str.add(optionB);str.add(optionC);str.add(optionD);str.add(optionE);str.add(optionF);str.add(optionG);List<QuestionOption> optionList = new ArrayList<>();for (int k = 0; k < str.size(); k++) {// 如果选项为空字符串则不添加该选项if (!"".equals(str.get(k).trim())) {QuestionOption option = new QuestionOption();option.setAddTime(new Date());option.setOptAnswer(question.getIsAsr());option.setOptContent(str.get(k).trim());option.setQstId(question.getId());char data[] = { backchar(AASC += 1) };option.setOptOrder(String.valueOf(data));optionList.add(option);}}Map<String, List<QuestionOption>> 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 excel --><dependency><groupId>poi</groupId><artifactId>poi-2.5.1-final</artifactId><version>20040804</version></dependency><!-- poi excel --><dependency><groupId>org.apache.ant</groupId><artifactId>ant</artifactId><version>1.9.3</version></dependency>

数据库插入

<insert id="addOptionBatch" parameterType="java.util.HashMap">INSERT INTO nxb_exam_options (<include refid="exam_options_columns" />) VALUES<foreach collection="optionList" index="index" item="item"separator=",">(#{item.id},#{item.qstId},#{item.optContent},#{item.optOrder}, #{item.optAnswer},#{item.addTime})</foreach></insert>

java excel 导入试题相关推荐

  1. java Excel导入导出工具类 及使用demo

    java Excel导入导出工具类 及使用demo 前言:相信进来的都是想尽快解决问题的,话不多说,按照以下步骤来,可以操作导出excel到本地,导入同理,自行学习.步骤一:直接复制以下excel工具 ...

  2. java Excel 导入 IllegalStateException 异常处理 不同的数据类型

    问题描述 最近做一个Excel导入,但是在java后台接受的时候,提示类型不正确 java.lang.IllegalStateException: Cannot get a FORMULA value ...

  3. java excel导入校验_excel导入前校验

    问题描述: 遇到客户提出过问题,能否在导入前对导入的excel内容进行校验,满足条件后才能导入到报表中. 解决思路: 在导入excel中首先要将excel的数据读入到报表文件中的excelReport ...

  4. Java Excel导入和导出(支持xls导入,xlsx导入,图片导出,百万数据量导出)

    免费源码下载(提取码:qdhy) 工程结构目录 所需JAR包 <dependencies><!-- JUNIT 测试 --><dependency><grou ...

  5. java excel导入并多线程批量插入数据库

    最近写了个excel导入并多线程持久化到数据库的功能,捣鼓了一天才弄好,先记录下来防止自己忘了. (1)先controller类中方法. @AccessLog@ApiOperation(value = ...

  6. java excel导入太慢_[Java] 高效快速导入EXCEL数据

    public voidaddAll(String url){//生成一个备用码 String guid=RandomUtils.myGetNo(9);//将excel数据转为集合并以100条每次的节奏 ...

  7. java excel 导入 加校验_POI实现excel各种验证和导入的思路总结

    制定标准 导入总是与导出相辅相成的,无规矩不成方圆.所谓的标准都是大家一同来维护和遵守的,那么首先就是制定一个模板. 这样可以减少验证的工作量. 例如时间的规范[yyyy-MM-dd],获取单元格的时 ...

  8. java Excel导入、自适应版本、将Excel转成Listmap对象

    转载:http://blog.csdn.net/u012662357/article/details/58593020 最近在web开发中遇到excel批量导入,在网上搜了下很少有将excel直接转成 ...

  9. java excel 导入导出_java中excel文件的导入和导出

    如有需要可以加我Q群[308742428]大家一起讨论技术,提供技术支持. 后面会不定时为大家更新文章,敬请期待. 前端上传excel文件到后台,后台接收后保存数据到数据库. 这里需要说明的一点是前端 ...

  10. java excel 导入 加校验_【JavaWeb】导入Excel并进行校验

    一.需要实现的目标 1.界面编写 2.导入表读取表名,进行校验,后台匹配(判断此表的名称是否能够模糊匹配上) 3.确定表存在,读取其中的数据,暂存 4.正则表达式数据校验(判断是否已存在,数据是否符合 ...

最新文章

  1. 人工智能创意赛复选赛成绩单
  2. linux shell ls xargs rm 组合删除文件
  3. 调试寄存器 原理与使用:DR0-DR7
  4. CentOS忘记密码
  5. 详解/etc/profile、/etc/bash.bahsrc、~/.profile、~/.bashrc的用途
  6. jscript错误代码及相应解释大全
  7. 【洛谷 P4051】 [JSOI2007]字符加密(后缀数组)
  8. 如此理解面向对象编程
  9. tomcat高版本之URL解析异常解决
  10. NVIDIA PhysX宣布正式开源 最强物理仿真引擎
  11. 遇到 oracle 错误 25153,EXP时,出现3113的错误,不知道怎么解决?
  12. messagebox 全部使用_你一定要知道的Windows 10系统的使用技巧
  13. 银行业务调度系统学习
  14. 微软 Exchange 服务器被滥用于内部邮件回复链攻击
  15. 脑洞大开!把 14 亿中国人拉到一个微信群 ?
  16. 家居照明行业网络营销怎么搞?
  17. 大恒MER-1070-10GC相机 LINUX环境 QT开发记录
  18. Alarm机制-学习记录
  19. JS基础 Set 用于存储任何类型的唯一值
  20. hadoop启动后某些节点未启动,hadoop主节点无法启动datanode DataNode

热门文章

  1. SVG和G语言的混合显示引擎
  2. 32G内存服务器如何设置虚拟内存,大内存服务器设置虚拟内存
  3. ADAMS2016启动证书错误解决
  4. css字体浏览(转)
  5. Unity游戏资源逆向工具
  6. Magisk 安装error
  7. excel相同字段多行合并_EXCEL里如何快速把多行数据合并为一行并以逗号隔开?...
  8. JSONP 的工作原理
  9. 初学视觉学习笔记----打开摄像头遇到的问题
  10. 软考:软件设计师(中级)