Spring boot 上传文件以及解析Excel

最近工作忙,产品在推广阶段,市场那别的需求猛如虎,而且还使必须做的,基本上两天就要完成一个需求.压力大啊.其中就用到了解析Excel的东西和生成Excel的技术,当然这些东西以前用过,当再次用的时候发现自己忘了,看来知识还是需要记录的.下面就将这次用到的技术做一个记录,是希望可以帮到其他人.

我们公司用的是Spring boot 我就集成POI完成了这次任务,使用IEDA搭建Spring boot特别简单,网上一大把一大把.在这里就不介绍了.

一.Maven坐标

下面是需要的Maven 坐标

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!-- web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- thmleaf模板依赖. -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--test-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--解析Excel-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.14</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.14</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.14</version>
        </dependency>
        <!--糊涂工具类-->
        <dependency>
            <groupId>com.xiaoleilu</groupId>
            <artifactId>hutool-all</artifactId>
            <version>3.3.2</version>
        </dependency>

        <!--使用IDEA插件@Data自动-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
            <scope>provided</scope>
        </dependency>
        <!--解析json-->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.2</version>
        </dependency>

以上是需要用到的maven坐标,并将每一个的依赖的作用加了注释.

二.文件的的上传

1.文件的上传的配置

/**
 * <p>
 * 类说明
 * </p>
 *
 * @author Alemand
 * @since 2018/3/19
 */
@Configuration
public class UploadFileProperties extends WebMvcConfigurerAdapter {

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 设置文件大小限制 ,超出设置页面会抛出异常信息,
        // 这样在文件上传的地方就需要进行异常信息的处理了;
        factory.setMaxFileSize("128MB"); // KB,MB
        /// 设置总上传数据总大小
        factory.setMaxRequestSize("256MB");
        //设置文件路径
        //factory.setLocation("");
        return factory.createMultipartConfig();
    }
}
2.文件上传的前台页面编写
<!DOCTYPE html>
<html>
<head>
<title>文件上传示例</title>
</head>
<body>
    <h2>文件上传示例</h2>
    <hr/>
    <form method="POST" enctype="multipart/form-data" action="/resolve/upload">
        <p>
            文件:<input type="file" name="file" />
        </p>
        <p>
            <input type="submit" value="上传" />
        </p>
    </form>
</body>
</html>
 
 

3.Controller的编写

/**
 * <p>
 * 类说明
 * </p>
 *
 * @author Alemand
 * @since 2018/3/19
 */
@RestController
@RequestMapping("/resolve")
public class ResolveExcelController {


    @Resource(name = "resolveExcelServiceImpl")
    private ResolveExcelService resolveExcelService;

    /**
     * 文件上传
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public ApiResponse uploadExcel(@RequestParam("file") MultipartFile file) {
        Object result;
        try {
            result = resolveExcelService.resolveExcel(file);
            //如果需要将文件放到服务其中加以下代码
           /* try {
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(new File(file.getOriginalFilename())));
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }*/
        } catch (BusinessException e) {
            e.printStackTrace();
            return ApiResponse.failOf(-1, e.getErrMsg());
        }
        return ApiResponse.successOf(result);
    }


}

4.Service层的编写要在Service解析Excel在这里我将解析到的数据封装到了一个对象

下面是我的对象字段

@Data
public class ReqImportClient {

    @SerializedName("userName")
    @Expose
    private String userName;

    @SerializedName("loginName")
    @Expose
    private String loginName;
    @SerializedName("password")
    @Expose
    private String password;
    @SerializedName("groupID")
    @Expose
    private String groupID;
    
}

@Service("resolveExcelServiceImpl")
public class ResolveExcelServiceImpl implements ResolveExcelService {
    /**
     *打印日志
     */
    private static final Log logger = LogFactory.get();
    /**
     * 注册url
     */
    private static final String SUFFIX_2003 = ".xls";
    private static final String SUFFIX_2007 = ".xlsx";
    /**
     * 电话的正则
     */
    public static final String PHONE_NUMBER_REG = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[01356789]|18[0-9]|19[89])\\d{8}$";
    /**
     * 密码长度
     */
    public static final int passWardLength = 6;

    @Override
    public List<ReqImportClient> resolveExcel(MultipartFile file) throws BusinessException {


        List<ReqImportClient> list = new ArrayList<>();
        if (file == null) {
            throw new BusinessException(ReturnCode.CODE_FAIL, "对象不能为空");
        }
        //获取文件的名字
        String originalFilename = file.getOriginalFilename();
        Workbook workbook = null;
        try {
            if (originalFilename.endsWith(SUFFIX_2003)) {
                workbook = new HSSFWorkbook(file.getInputStream());
            } else if (originalFilename.endsWith(SUFFIX_2007)) {
                workbook = new XSSFWorkbook(file.getInputStream());
            }
        } catch (Exception e) {
            logger.info(originalFilename);
            e.printStackTrace();
            throw new BusinessException(ReturnCode.CODE_FAIL, "格式错误");
        }
        if (workbook == null) {
            logger.info(originalFilename);
            throw new BusinessException(ReturnCode.CODE_FAIL, "格式错误");
        } else {
            //获取所有的工作表的的数量
            int numOfSheet = workbook.getNumberOfSheets();
            //遍历这个这些表
            for (int i = 0; i < numOfSheet; i++) {
                //获取一个sheet也就是一个工作簿
                Sheet sheet = workbook.getSheetAt(i);
                int lastRowNum = sheet.getLastRowNum();
                //从第一行开始第一行一般是标题
                for (int j = 1; j <= lastRowNum; j++) {
                    Row row = sheet.getRow(j);
                    ReqImportClient reqImportClient = new ReqImportClient();
                    //获取电话单元格
                    if (row.getCell(0) != null) {
                        row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                        String longName = row.getCell(0).getStringCellValue();
                        //todo 正则比对
                        boolean matche = Pattern.matches(PHONE_NUMBER_REG, longName);
                        if (!matche) {
                            throw new BusinessException(ReturnCode.CODE_FAIL, "电话格式错误");
                        }
                        reqImportClient.setLoginName(longName);
                    }
                    //密码
                    if (row.getCell(1) != null) {
                        row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                        String passWard = row.getCell(1).getStringCellValue();
                        if (passWard.replace("", "").length() < passWardLength) {//校验密码长度
                            throw new BusinessException(ReturnCode.CODE_FAIL, "密码的格式有误");
                        }
                        reqImportClient.setPassword(passWard);
                    }
                    //姓名
                    if (row.getCell(2) != null) {
                        row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                        String userName = row.getCell(2).getStringCellValue();
                        reqImportClient.setUserName(userName);
                    }
                    if (row.getCell(3) != null) {
                        row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
                        String groupID = row.getCell(3).getStringCellValue();
                        reqImportClient.setGroupID(groupID);
                    }
                    list.add(reqImportClient);
                }
            }
        }
        return list;
    }


}

这样就将Excel解析完了,其实学会了是比较简单的.没有技术难度的.

最后附上Demo的地址gitHub



猜你喜欢

转载自blog.csdn.net/mypersonalsong/article/details/79756935