Upload Excel and parse

Compatible with 2007 and 2003 types of files, for example: this template has two footers:

                         


/**
     * Select list import method
     * File Upload
     * Upload and parse out the field, add it after parsing
     * Upload file field upfile
     * userGroupName user group name
     * appName application name
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile[]  files,@RequestParam String userGroupName,@RequestParam String applicationName
            , HttpSession session) throws IllegalStateException, IOException{
        UserGroup userGroup = new UserGroup();
        userGroup.setUserGroupName(userGroupName);
        userGroup.setApplicationName(applicationName);
        UapUser uapUser = (UapUser)session.getAttribute("USER");
        if (null != uapUser) {
            userGroup.setCreationBy(uapUser.getLoginName());
        }
        System.out.println("***File upload***");
        MultipartFile excelFile = null;
        if(files!=null && files.length>0){
            excelFile = files[0];
        }else{
            return ResultGenerator.genCostomFailResult(ResultCode.DELETE_FAIL_ERROR, "No file uploaded");

        }

        System.out.println("***Parse excel upload to slave table***");
        //The parsed user id or mac address set
        List<String> idlist = new ArrayList<String>();
        List<String> maclist = new ArrayList<String>();
        String fileType = "";
        try {
            String fileName = excelFile.getOriginalFilename();
            fileType = fileName.substring(fileName.lastIndexOf(".") + 1,
                    fileName.length());
            System.out.print("The file type is "+fileType);
        } catch (Exception e) {

            fileType = "";
        }
        if (!fileType.toLowerCase().equals("xls")  && !fileType.toLowerCase().equals("xlsx")) {
            System.out.print("Format not supported");
            return ResultGenerator.genCostomFailResult(ResultCode.DELETE_FAIL_ERROR, "Unsupported file type");

        }

        // XSSF
        if("xlsx".equals(fileType)  || "xls".equals(fileType)){
            System.out.println("Start parsing"+fileType);
            Workbook wb = null;

            InputStream inp = excelFile.getInputStream();
            try {

                if(! inp.markSupported()) {
                    inp = new PushbackInputStream(inp, 8);
                }

                if(POIFSFileSystem.hasPOIFSHeader(inp)) {
                   wb = new HSSFWorkbook(inp);
                }else if(POIXMLDocument.hasOOXMLHeader(inp)) {
                   wb =  new XSSFWorkbook(OPCPackage.open(inp));
                }

                if (null == wb){
                    return ResultGenerator.genCostomFailResult(ResultCode.ADD_FAIL_ERROR,
                            "Import failed!");

                }
                Sheet macSheet = wb.getSheetAt(0);//mac地址
                Sheet idSheet = wb.getSheetAt(1);//用户id
                String mac = wb.getSheetName(0);// mac地址  Sheet1



                /*  String id = wb.getSheetName(1);//用户id  Sheet2*/
              // Parse the mac address
                System.out.println("parse mac address"+mac);
                for (int i = macSheet.getFirstRowNum()+1; i <= macSheet.getLastRowNum(); i++) {
                    Row row = macSheet.getRow(i);
                    Iterator cells = row.cellIterator();
                    while (cells.hasNext()) {
                        Cell cell = (Cell) cells.next();
                        String str = cell.getStringCellValue();
                        System.out.print(" " + str);
                        maclist.add(str);
                    }
                }
                //parse user id
                System.out.println("parse id address");
                for (int i = idSheet.getFirstRowNum()+1; i <= idSheet.getLastRowNum(); i++) {
                    Row row = idSheet.getRow(i);
                    Iterator cells = row.cellIterator();
                    while (cells.hasNext()) {
                      Cell cell = (Cell) cells.next(); //User Id may be a string or a pure number, not sure
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String str = cell.getStringCellValue();
                        System.out.println("内容"+cell.toString());
                        /*Cell cell = (Cell) cells.next();
                        String str = cell.getStringCellValue();
                        System.out.print(" " + str);*/
                        idlist.add(str);
                    }
                }


            } catch (Exception e) {
                System.out.print(e);
              // return ResultGenerator.genCostomFailResult(ResultCode.ADD_FAIL_ERROR, "Add failed");
                // BusinessServiceException("Unknown reason! When saving the Excel file, please don't finally position the mouse on the column in Excel where the drop-down value can be selected.");
            }
        }




        System.out.println("User id list"+idlist);
        System.out.print("mac列表 "+maclist);
        userGroup.setUserIdList(idlist);
        userGroup.setMacList(maclist);
      UserGroup dealUserGroup = userGroupService.dealExcelImportUserGroup(userGroup);
      if(dealUserGroup==null){
          return ResultGenerator.genCostomFailResult(ResultCode.ADD_FAIL_ERROR, "Add failed, application name does not exist");

      }
        int a = userGroupService.addEcxelImportUserGroup(dealUserGroup);
      if(a==-2){
          return ResultGenerator.genCostomFailResult(ResultCode.ADD_FAIL_ERROR, "Add failed, the user group name already exists");

      }else  if (a <= 0) {
            return ResultGenerator.genCostomFailResult(ResultCode.ADD_FAIL_ERROR, "Add failed");
        }
        return ResultGenerator.genSuccessResult("Added successfully");
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325363983&siteId=291194637