栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA 实现(EasyExcel 通过模板 导入、导出、下载模板)功能

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA 实现(EasyExcel 通过模板 导入、导出、下载模板)功能

目录

1、介绍

2、添加pom.xml依赖

3、新建excel导入模板

4、导入操作

5、导出操作

6、工具类


1、介绍

我这里举例 Student 和 StudentExcel
Student 就是你数据库表的对象
StudentExcel 是你导入进来的Excel对应的字段 ,为啥写他,用来校验数据格式,判空处理。
你要把你导入进来的对象 StudentExcel 转换成 你业务对象 Student ,转换方式我下面有工具类

官方文档地址:EasyExcel官方文档 - 基于Java的Excel处理工具 | Easy Excel 

2、添加pom.xml依赖


    com.alibaba
    easyexcel
    3.0.5

 

3、新建excel导入模板

注意:这个模板是你自己定义的写好的直接扔到项目里就行,不要直接扔在resources目录下,创一个文件夹(template)放进去,用于导入时下载模板使用。如下图:

 

新建StudentExcel.java  Excel对象

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.io.Serializable;


@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@HeadRowHeight(value = 40)
public class StudentExcel implements Serializable {

    private static final long serialVersionUID = -5144055068797033748L;

    
    @ExcelProperty(value = "姓名", index = 0)
    @ColumnWidth(value = 20)
    @NotBlank(message="姓名不能为空")
    private String name;

    
    @ExcelProperty(value = "性别r1:男 :2女", index = 1)
    @ColumnWidth(value = 20)
    @NotBlank(message="性别不能为空")
    private String gender;

    
    @ExcelProperty(value = "出生日期", index = 2)
    @ColumnWidth(value = 20)
    @NotBlank(message="出生日期不能为空")
    @DateTimeStr(format ="yyyy-MM-dd", message = "出生日期格式错误,正确格式为:yyyy-MM-dd")
    private String birthday;

    
    @ExcelProperty(value = "年龄", index = 3)
    @ColumnWidth(value = 20)
    @NotBlank(message="年龄不能为空")
    private String age;


    
    @ExcelProperty(value = "身份证号码", index = 4)
    @ColumnWidth(value = 20)
    @NotBlank(message="身份证号码不能为空")
    @Pattern(regexp = "^\d{15}$|^\d{17}[0-9Xx]$",message = "身份证格式不正确!")//长度18,0-9
    private String cardNo;

    
    @ExcelProperty(value = "联系电话", index = 5)
    @ColumnWidth(value = 20)
    @NotBlank(message="联系电话不能为空")
    @Pattern(regexp = "^[1][3,4,5,7,8][0-9]{9}$",message = "联系电话格式不正确!")//长度11
    private String telephone;

    
    @ExcelProperty(value = "是否已婚", index = 6)
    @ColumnWidth(value = 20)
    @NotBlank(message="是否已婚不能为空")
    private String marryStatus;


    
    @ExcelProperty(value = "银行卡号", index = 8)
    @ColumnWidth(value = 20)
    @NotBlank(message="银行卡号不能为空")
    @Pattern(regexp = "^([1-9]{1})(\d{14}|\d{18})$",message = "银行卡号格式不正确!")//长度11
    private String bankCardNo;

}

校验日期注解

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = CheckDateTimeCaseValidator.class)
public @interface DateTimeStr {

    String message() default "{javax.validation.constraints.DateTimeStr.message}";


    String format() default "yyyy-MM-dd";

    Class[] groups() default {};

    Class[] payload() default {};
}


新建Student 对象(你的业务对象,就是数据库对应的对象) 

public class Student implements Serializable {

    private static final long serialVersionUID = -5144055068797033748L;

    
    private String name;

    
    private int gender;

    
    private Date birthday;

    
    private int age;


    
    private String cardNo;

    
    private String telephone;

    
    private int marryStatus;

    
    private String bankCardNo;

    
    private Date dimissionDate;
}

Controller 代码:

    
    @RequestMapping(value="/import")
    public void importExcel(HttpServletRequest request, HttpServletResponse response,@RequestBody MultipartFile file) throws Exception {
        staffManageService.importExcel(file);
    }


    
    @RequestMapping(value="/export",method = RequestMethod.POST)
    public void batchExport(HttpServletResponse response) throws ParseException {
        staffManageService.export(response,staffRosterVo);
    }
    
    @GetMapping(value="/download")
    public void download(HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
        FileUtil.downloadExcel(request,response);
    }

这里的下载模板其实是Controller + FileUtil 工具类,下载模板的操作已经做好了,工具类见如下操作:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

public class FileUtil {

    
    public static boolean checkFileSize(Long len, int size, String unit) {
//        long len = file.length();
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }
	
	
    public static void downLoadFile(String filePath, String fileName, HttpServletResponse response) {
        try (InputStream inStream = new FileInputStream(filePath);
             OutputStream os = response.getOutputStream()) {
            response.setHeader("Content-Disposition", "attachment; fileName=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            byte[] buff = new byte[100];
            int len;
            while ((len = inStream.read(buff)) > 0) {
                os.write(buff, 0, len);
            }
            os.flush();
        } catch (Exception e) {
            throw new BusinessException(ResponseResultEnum.FILE_IMPMOT_SIZE.getCode(), ResponseResultEnum.FILE_IMPMOT_SIZE.getMsg());
        }
    }

	//下载模板
    public static void downloadExcel(HttpServletRequest request, HttpServletResponse response){
        //方法一:直接下载路径下的文件模板(这种方式貌似在SpringCloud和Springboot中,打包成JAR包时,无法读取到指定路径下面的文件,不知道记错没,你们可以自己尝试下!!!)
        try {
        	//文件名称
            String fileName = "excelImportTemplate.xlsx";
            //设置要下载的文件的名称
            response.setHeader("Content-disposition", "attachment;fileName=" + fileName);
            //通知客服文件的MIME类型
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            //获取文件的路径
            String filePath = FileUtil.class.getResource("/template/" + fileName).getPath();
            FileInputStream input = new FileInputStream(filePath);
            OutputStream out = response.getOutputStream();
            byte[] b = new byte[2048];
            int len;
            while ((len = input.read(b)) != -1) {
                out.write(b, 0, len);
            }
            //修正 Excel在“xxx.xlsx”中发现不可读取的内容。是否恢复此工作薄的内容?如果信任此工作簿的来源,请点击"是"
            response.setHeader("Content-Length", String.valueOf(input.getChannel().size()));
            input.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

}

4、导入操作

 导入代码:

    
    @Override
    public void importExcel(MultipartFile file) throws Exception {
            List ExcelList = null;
            String validate = "";
            //校验文件大小 100M
            boolean size = FileUtil.checkFileSize(file.getSize(), 100, ResponseResultEnum.FILE_UNIT.getMsg());
            if(size == false){
                //文件过大啦,只能100M
            }
            //excel读取数据
            staffExcelList = EasyExcel.read(new BufferedInputStream(file.getInputStream())).head(StaffDataExcel.class).sheet().doReadSync();
            if (ExcelList.size() > 1000) {
                //最多导入1000条哦
            }
            // excel数据校验
            validate = ValidatorUtils.beanValidate(ExcelList);
            if(!validate.equals("success")){
                //参数异常提示  如:姓名不能为空哦~
            }
            //把Excel数据转换成你对应的对象集合List
            List studentList = ExcelUtil.excelListConvertList(ExcelList);
            //拿到数据后就可以 入库操作啦 -----我自己的入库就不给你们写了
            StudentService.importExcel(studentList );
    }

5、导出操作

导出代码

    
    @Override
    public void export(HttpServletResponse response) throws ParseException {
        String fileName = "导出的文件名称";
        String sheetName = "导出的 sheetName ";
       
        List list = studentService.findList();
        List studentExcelList = ExcelUtil.listConvertexcelList(list );
        try {
           ExcelUtil.writeExcel(response, studentExcelList , fileName, sheetName, StaffDataExportExcel.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

6、工具类

工具类 FileUtil 在上面已经提到...

工具类 ValidatorUtils (导入的时候参数校验)

import cn.hutool.core.lang.Assert;
import org.apache.commons.lang3.ObjectUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.*;

public class ValidatorUtils {
    private static final Validator validator = Validation.buildDefaultValidatorFactory()
            .getValidator();

    public static String beanValidate(@Valid Object obj) throws IllegalArgumentException {
        if (obj instanceof Collection) {
            ValidCollection validCollection = new ValidCollection<>();
            validCollection.setList((Collection) obj);
            return validate(validCollection);
        } else {
            return validate(obj);
        }
    }

    public static String validate(@Valid Object obj) {
        try {
            Map validatedMsg = new HashMap<>();
            Set> constraintViolations = validator.validate(obj);
            String validate = "";
            String message = "";
            for (ConstraintViolation c : constraintViolations) {
                validate = c.getPropertyPath().toString();
                validate = validate.substring(5,6);
                int unm = Integer.valueOf(validate) +1;
                validatedMsg.put( "表格第"+unm+"条 ", c.getMessage());
            }
            Assert.isTrue(ObjectUtils.isEmpty(constraintViolations), validatedMsg.toString());
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return "success";
    }


    private static class ValidCollection {
        @Valid
        private Collection list;

        public Collection getList() {
            return list;
        }

        public void setList(Collection list) {
            this.list = list;
        }
    }
}

 

工具类 ExcelUtil (Excel转换)

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtil {
    
    public static void writeExcel(HttpServletResponse response, List data, String fileName, String sheetName, Class clazz) throws Exception {
        //表头样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置表头居中对齐
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //内容样式
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //设置内容靠左对齐
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        EasyExcel.write(getOutputStream(fileName, response), clazz).excelType(ExcelTypeEnum.XLSX).sheet(sheetName).registerWriteHandler(horizontalCellStyleStrategy).doWrite(data);
    }
    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        return response.getOutputStream();
    }

	
    public static List excelListConvertList(List studentExcelList) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List list = new ArrayList<>();
        for (StudentExcel s : studentExcelList) {
            Student student = Student.builder()
                    .name(staffDataExcel.getname())
                    .age(staffDataExcel.age())
                    .city(staffDataExcel.getCity())
                    .sex(staffDataExcel.getsex().equals("男")?1:2)
                    .birthday(sdf.parse(staffDataExcel.getBirthday()))
                    .build();
            list.add(student);
        }
        return list ;
    }

	
    public static List listConvertexcelList(List student) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List list= new ArrayList<>();
        for (Student s : student) {
            StudentExcel excel = StudentExcel.builder()
                    .name(staffDataExcel.getname())
                    .age(staffDataExcel.age())
                    .city(staffDataExcel.getCity())
                    .sex(staffDataExcel.getsex().equals("男")?1:2)
                    .birthday(sdf.parse(staffDataExcel.getBirthday()))
                    .build();
                    .build();
            list.add(excel);
        }
        return list;
    }

}


到这里就结束了,感谢支持...

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号