Spring Boot+Layui 导入Excel文件

1、首先是pom.xml,添加依赖。

		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.17</version>
		</dependency>

2、Controller层代码

@ResponseBody
@RequestMapping("/importExcel")
	public WebResult importExcel(@RequestParam("file") MultipartFile file) throws IOException {

		int success = 0;
		try {
			ExcelData data = ExcelRead.getInst().parse(file.getInputStream(), file.getOriginalFilename(), false, true);
			List<String[]> datas = data.getDatas();
			List<JSONObject> errorRes = new ArrayList<>();

			for (String[] strings : datas) {//循环出每一行的信息
				String stuno = strings[0].trim();
				String name = strings[1].trim();
				if(stuno.isEmpty() || name.isEmpty()){
					continue;
				}
				String courcename = strings[2].trim();
				Float score = new Float(strings[3].trim());
				String type = strings[4].trim();

				String error = "";
				Stu stuInfo = stuService.getByNameAndStuno(name, stuno);
				if (null == stuInfo) {
					error += "名字或学号匹配不到学生信息";
				}
				if (StringUtils.isNotBlank(error)) {
					JSONObject o = new JSONObject();
					o.put("name", name);
					o.put("stuno", stuno);
					o.put("error", error);
					errorRes.add(o);
				} else {
					//根据课程名称查出课程id
					Course course = courseService.findCidbyCname(courcename);
				   //for循环执行插入的方法
					stuScoService.insertScore(stuno,course.getCourseId(),score,type);
				}
			}
		} catch (Exception e) {
			return WebResult.getError(WebResult.FAIL, e.getMessage());
		}
		return WebResult.getSuccess("操作成功" + success + "个");
	}

3、页面

<button type="button" class="layui-btn layui-btn-primary" id="uploadExcel">批量导入</button>
layui.use('upload', function() {
      var upload = layui.upload;
      upload.render({
          elem: '#uploadExcel'
          , url:'importExcel'//路径这看你怎么配置的怎么写
          , field:"file"
          , exts: 'xls|xlsx|xlsm|xlt|xltx|xltm'
          , done: function (res) {
              if(res.success){
                  parent.layer.msg('导入成功!', {icon: 1,time:2000,shade:0.2});
              }
          }
      });
  });

这里我说一下我这页面遇到的坑,我也是刚接触这个Layui框架不久,我第一次调试的时候的代码,我在标签对里添加了onclick方法,然后就是请求不到接口,直接用上面的就好了,我想应该是有id了就不用再包一层这个方法了吧

function importExcel (argument) {
      layui.use('upload', function() {
      var upload = layui.upload;
      upload.render({
          elem: '#uploadExcel'
          , url:'importExcel'//路径这看你怎么配置的怎么写
          , field:"file"
          , exts: 'xls|xlsx|xlsm|xlt|xltx|xltm'
          , done: function (res) {
              console.log(res);
          }
      });
  });

  }

注意事项
1、代码有写的不好的地方可以评论区告诉我,虚心接受。
2、代码中有涉及到的类,如果有需要可以加我qq(2253978324),备注好,有空就会回复。

你可能感兴趣的:(java)