JAVA操作excel(读XSSFWorkbook)

1:接收文件

        @Override
    @RequestMapping(value = "/syncUserInfo", method = RequestMethod.POST)
    @ResponseBody
    public Response syncUserInfo(@RequestParam("file") MultipartFile file) {

        // 分析文件
        StopWatch clock = new StopWatch();
        clock.start();
        userService.syncUserInfo(file);
        clock.stop();
        long handlingTime = clock.getTime();
        logger.info("上传成功, 上传文件耗时: " + handlingTime + "ms");
        return Response.buildSuccess();
    }

2:解析excel数据


        @Override
    public void syncUserInfo(MultipartFile file) {
        String fileExtension = Files.getFileExtension(file.getOriginalFilename());
        if (!"XLSX".equalsIgnoreCase(fileExtension)) {
            throw new Exception();
        }
        try {
            XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
            List<UserInfo> userInfos = getUserInfos(wb.getSheetAt(0));
            logger.info("userInfos:{}", userInfos.size());
                }catch(Exception ex){

                }

private List<GlideSpPay> getGlideSpPay(GlideSpTotal glideSpTotal, XSSFSheet sheet) throws Exception {
        List<GlideSpPay> glideSpPays = Lists.newArrayList();
        Boolean isFen = glideSpTotal.isFen();
        for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
            XSSFRow row = sheet.getRow(i);
            if (row == null || row.getCell(0) == null) {
                continue;
            }
            String policyNoExt = getStringCellValue(row.getCell(0));
            if (StringUtils.isNotEmpty(policyNoExt)) {
                GlideSpPay glideSpPay = new GlideSpPay();
                glideSpPay.setPolicyNoExt(policyNoExt);
                glideSpPay.setStageNum(Integer.parseInt(getStringCellValue(row.getCell(1))));
                Long premium = null;
                if (!isFen) {
                    premium = Math.round(Double.parseDouble(getBigDecimalCellValue(row.getCell(2))) * 100);
                } else {
                    premium = Math.round(Double.parseDouble(getBigDecimalCellValue(row.getCell(2))));
                }
                glideSpPay.setAmt(premium);
                if (row.getCell(3) != null) {
                    Date date = DateUtil.getJavaDate((row.getCell(3).getNumericCellValue()));
                    glideSpPay.setClearTime(date);
                }
                glideSpPays.add(glideSpPay);
            }
        }

        return glideSpPays;
    }


protected String getBigDecimalCellValue(XSSFCell cell) {
        switch (cell.getCellType()) {
        case XSSFCell.CELL_TYPE_STRING:
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        case XSSFCell.CELL_TYPE_NUMERIC:
            return "" + cell.getNumericCellValue();
        }
        return "";
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容