Ajax上传.xlsx文件并解析
1、首先必须配置bean
1 2 3 4 5 6 7 | < bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> < property name="maxUploadSize" value="10485760"/> < property name="resolveLazily" value="true"/> < property name="maxInMemorySize" value="4096"/> < property name="defaultEncoding" value="UTF-8"/> </ bean > |
2、ftl页面代码
1 2 3 4 | < form id="fileForm" method="post" enctype="multipart/form-data"> < input type="text" id="someText" name="someText"> < input type="file" name="file" id="file"> </ form > |
3、js代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | var someText= $("#someText").val(); var file = $("#file")[0].files[0]; //获取标签值好像函数与浏览器不兼容,网上的大多是通过$("#file").files[0]获取, 我这里必须通过$("#file")[0].files[0]才能获取到值 var formData = new FormData(); formData.append('someText', someText); formData.append('file', file); $.ajax({ type:"post", url:'请求路径', data:formData, dataType:'json', cache:false, contentType: false, processData: false, success: function(data) { // 结果处理 } }); |
4、后台代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | @RequestMapping (value = "路径" , method = { RequestMethod.GET, RequestMethod.POST }) @ResponseBody public Object uploadFile( @RequestParam (value = "someText" , required = false ) String someText, @RequestParam (value = "file" , required = false ) MultipartFile file, HttpServletRequest request) { //required = false才能获取到值 XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream()); XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream()); for ( int numSheet = 0 ; numSheet < workbook.getNumberOfSheets(); numSheet++) { XSSFSheet sheetAt = workbook.getSheetAt(numSheet); if (sheetAt == null ) { continue ; } // 循环行Row for ( int rowNum = 0 ; rowNum <= sheetAt.getLastRowNum(); rowNum++) { XSSFRow row = sheetAt.getRow(rowNum); if (row == null ) { continue ; } // 循环列Cell for ( int cellNum = 0 ; cellNum <= row.getLastCellNum(); cellNum++) { //在此可进行获取单元格值并入库 getValue(row,cellNum); } } } } //单元格类型转换并获取值 private String getValue(XSSFRow row, int cellNum) { XSSFCell cell = row.getCell(cellNum); if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) { return String.valueOf(cell.getBooleanCellValue()); } else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) { return String.valueOf(( int ) cell.getNumericCellValue()); } else { return String.valueOf(cell.getStringCellValue()).equals( "" ) ? "" : String .valueOf(cell.getStringCellValue()); } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步