现有的做法是用MultipartFile类读取excel文件以后用transferTo()转存到硬盘上,请问能不能不用转存到硬盘直接用File类读取,试过将其强制转换成File类型结果报错。
目前做法的代码:
Controller层:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | @RestController @RequestMapping ( "/excel" ) public class ExcelFileController { //注入excel服务 @Resource private ExcelService excelService; @RequestMapping (value = "/upload" ,method = RequestMethod.POST) public String ExcelFileUpload( @RequestParam ( "file" ) MultipartFile file){ if (excelService.uploadExcelToSQL(file)){ return "true" ; } else { return "false" ; } } } |
Service层实现类:
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 39 40 41 42 43 44 45 46 47 48 49 50 | @Service public class ExcelSerivceImpl implements ExcelService { /** * 将读取到的Excel文件存入数据库中接口实现 */ @Override public boolean uploadExcelToSQL(MultipartFile file) { if (!file.isEmpty()){ Workbook workBook = null ; File excelfile = new File( "E:/upload/" + file.getOriginalFilename()); try { file.transferTo(excelfile); } catch (Exception e) { excelfile.delete(); e.printStackTrace(); } if (file.getOriginalFilename().toLowerCase().endsWith( "xls" )){ try { workBook =ExcelUtil.getWorkbook( 0 , FileUtils.openInputStream(excelfile)); } catch (IOException e) { excelfile.delete(); e.printStackTrace(); } } else if (file.getOriginalFilename().toLowerCase().endsWith( "xlsx" )){ try { workBook =ExcelUtil.getWorkbook( 1 , FileUtils.openInputStream(excelfile)); } catch (IOException e) { excelfile.delete(); e.printStackTrace(); } } else { return false ; } List<List<String>> excelString = ExcelUtil.getExcelString(workBook, 0 , 0 , 0 ); for (List<String> row : excelString){ for (String cellValue : row){ System.out.print(cellValue+ ", " ); } System.out.println(); } if (excelfile.isFile()&& excelfile.exists()){ excelfile.delete(); } return true ; } else { return false ; } } } |
【毕设】SSM全面梳理,前后端分离,zTree 和复杂SQL打造权限系统,解惑MyBatis和RESTful
了解课程