1.前端代码
$("#upload").on('click', function() { var formData = new FormData(); var name = $("#uploadFile").val(); formData.append("fileupload", $("#articleImageFile")[0].files[0]); formData.append("name", name); //这个地方可以传递多个参数 if(name == null || name == ''){ alert("请选择上传文件"); } $.ajax({ type: 'post', url: commenUrl + "/fileUpload", async: false, data: formData, // 告诉jQuery不要去处理发送的数据 processData: false, // 告诉jQuery不要去设置Content-Type请求头 contentType: false, beforeSend: function() { console.log("正在进行,请稍候"); }, success: function(data) { if(data.code == 0) { alert("导入成功"); $("#myModal").modal('hide');//隐藏模态框 }else { alert("导入失败"); }; } }); });
2.控制层代码
@RequestMapping(value = "/fileUpload", method = RequestMethod.POST) @ResponseBody public void fileUpload(@RequestParam("fileupload")MultipartFile fileupload, HttpServletRequest request, HttpServletResponse response, ApiJsonResult result) { try { result = uploadService.fileUpload(fileupload,result); } catch (Exception e) { e.printStackTrace(); result.setCode(StatusCodeEnum.EXTREMELY.getCode()); result.setMsg(StatusCodeEnum.EXTREMELY.getDesc()); } JsonWebPrintUtils.printApiResult(request, response, result); }
3.实现代码
excel中存在纯数字的数据时,可以使用getNumericCellValue()取值,或者使用setCellType(Cell.CELL_TYPE_STRING)统一设置为字符串格式读取。实际应用中可根据实际情况在读取过程中对读取到的数据进行校验返回错误信息到客户端。
@Override public ApiJsonResult fileUpload(MultipartFile fileupload, ApiJsonResult result) throws IOException{
//获取文件名 String fileName = fileupload.getOriginalFilename(); Workbook workbook = getWorkbook(fileName,fileupload);
if(fileName.endsWith(XLS)) {
//2003
workbook = new HSSFWorkbook(fileupload.getInputStream());
}else if(fileName.endsWith(XLSX)) {
//2007
workbook = new XSSFWorkbook(fileupload.getInputStream());
}
//创建工作表sheet Sheet sheet = this.getSheet(workbook, 0);
//获取sheet中数据的行
int rows = sheet.getPhysicalNumberOfRows();
List<UploadTest> lsit = new ArrayList<>();//用于存放读取到的数据
for(int i=1;i<row.length;i++){//从第二行开始读取数据
Row row = sheet.getRow(i);
row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);//设置读取数据类型为string
row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);//设置读取数据类型为string
String value1 = row.getCell(0).getStringCellValue();//第一列的值
String value2 = row.getCell(1).getStringCellValue();//第二列的值
UploadTest test = new UploadTest(); //创建实体类接受值
test.setPig(value1);
test.setDog(value2);
list.add(test);
}
//将数据写入数据库
...............省略
return this.getCarAndDeviceBindData(sheet,result); }