springboot2.0 有条件的导入

springboot2.0 有条件的导入

  1. 导出控制器方法:post请求
  public Object exportStudent(@RequestBody Map map,HttpServletRequest request, HttpServletResponse response) {
        String loginName = (String) map.get("loginName"); //登录名称
        String downloadName =(String) map.get("downloadName"); //文件名称
        String title = (String) map.get("title"); //标题
        String sheetName = (String) map.get("sheetName"); // sheet名称
        if (StringUtils.isBlank(title) || StringUtils.isBlank(sheetName) || StringUtils.isBlank(downloadName)) {
            return new ResponseInfo(505,"标题、sheet名称、文件名称不能为空");
        }
        //条件查询数据集合
        List<Student> studentList = studentService.exportStudentByConditions(loginName);
        for (Student student : studentList) {
            if (student.getTel() == null) {
                student.setTel("无");
            }
            if (student.getEmail() == null) {
                student.setEmail("无");
            }
        }
        //导出到Excel
        ExcelUtils.exportExcel(studentList, title, sheetName, Student.class, downloadName+".xls", response);
        return new ResponseInfo(200,"导出成功");
    }
  1. 导入控制器方法:post请求 可以导入为空的列
    public Object importStudent(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        if (file.isEmpty()) {
            return new ResponseInfo(505,"文件不能为空");
        }
        try {
            List<Student> studentList = ExcelUtils.importExcel(file, Student.class);
            //----------------在此执行逻辑操作
            return new ResponseInfo(200,"导入成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseInfo(505,"导入失败");
    }
  1. 工具类
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

public class ExcelUtils {

    /**
     * 导出
     * @param list 数据
     * @param title 标题
     * @param sheetName sheet名称
     * @param pojoClass pojo类型
     * @param fileName 文件名称
     * @param isCreateHeader 是否创建表头
     * @param response
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response){
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);

    }

    /**
     *  导出
     * @param list 数据
     * @param title 标题
     * @param sheetName   sheet名称
     * @param pojoClass   pojo类型
     * @param fileName 文件名称
     * @param response
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response){
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }

    /**
     * 导出
     * @param list  数据
     * @param fileName 文件名称
     * @param response
     */
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
        defaultExport(list, fileName, response);
    }

    /**
     *  默认的 导出
     * @param list  数据
     * @param pojoClass  pojo类型
     * @param fileName   文件名称
     * @param response
     * @param exportParams  导出参数
     */
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
        if (workbook != null){

        }
        downLoadExcel(fileName, response, workbook);
    }

    /**
     * 下载
     * @param fileName  文件名称
     * @param response
     * @param workbook  文件名称
     */
    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载1
     *
     * @param fileName 文件名称
     * @param response
     * @param workbook excel数据
     */
    private static void downLoadExcel1(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLSX.getValue(), "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }


    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }

    /**
     * 导入
     * @param filePath  excel文件路径
     * @param titleRows  标题行
     * @param headerRows  表头行
     * @param pojoClass  pojo类型
     * @param 
     * @return
     */
    public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){
        if (StringUtils.isBlank(filePath)){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        }catch (NoSuchElementException e){
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 导入
     * @param file   excel文件
     * @param titleRows  标题行
     * @param headerRows  表头行
     * @param pojoClass  pojo类型
     * @param 
     * @return
     */
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
        if (file == null){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        }catch (NoSuchElementException e){
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * excel 导入
     *
     * @param file      excel文件
     * @param pojoClass pojo类型
     * @param 
     * @return
     */
    public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass) throws IOException {
        return importExcel(file, 1, 1, pojoClass);
    }

    /**
     * excel 导入
     *
     * @param inputStream 文件输入流
     * @param titleRows   标题行
     * @param headerRows  表头行
     * @param needVerfiy  是否检验excel内容
     * @param pojoClass   pojo类型
     * @param 
     * @return
     */
    public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, boolean needVerfiy, Class<T> pojoClass) throws IOException {
        if (inputStream == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setSaveUrl("/excel/");
        params.setNeedSave(true);
        params.setNeedVerfiy(needVerfiy);
        try {
            return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new IOException("excel文件不能为空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }


    /**
     * Excel 类型枚举
     */
    enum ExcelTypeEnum {
        XLS("xls"), XLSX("xlsx");
        private String value;

        ExcelTypeEnum(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
}

  1. 实体类
public class Student implements Serializable {

    private static final long serialVersionUID=1L;

    @ApiModelProperty(value = "id")
    @TableId(value = "id",type = IdType.AUTO)
    private Long id;

    @ApiModelProperty(value = "账户")
    @Excel(name = "账号",width = 15,orderNum = "0")
    private String loginName;

    @ApiModelProperty(value = "姓名")
    @Excel(name = "姓名",width = 15,orderNum = "0")
    private String studentName;

    @ApiModelProperty(value = "用户头像")
    private String studentIcon;

    @ApiModelProperty(value = "密码")
    private String password;

    @ApiModelProperty(value = "shiro加密盐")
    private String salt;

    @ApiModelProperty(value = "手机号码")
   // @Excel(name = "手机号码",width = 20,orderNum = "2")
    private String tel;

    @ApiModelProperty(value = "邮箱地址")
   // @Excel(name = "邮箱地址",width = 25,orderNum = "3")
    private String email;

    @ApiModelProperty(value = "是否锁定")
    private Integer locked;

    private String remarks;

    /**
     * 注册时间
     */
    private Date registTime;


    private String createUser;


    @TableField(exist = false)
    @Excel(name = "班级",width = 15,orderNum = "0")
    private String clazzName;
  1. pom依赖
<dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>3.2.0</version>
        </dependency>

你可能感兴趣的:(springboot,导入导出,spring,boot,java)