现有的做法是用MultipartFile类读取excel文件以后用transferTo()转存到硬盘上,请问能不能不用转存到硬盘直接用File类读取,试过将其强制转换成File类型结果报错。
目前做法的代码:
Controller层:
@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层实现类:
@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
了解课程