SpringBoot整合easyexcel实现Excl导入导出

EasyExcel是一个基于Java的简单、省内存的读写Excel的开源项目。在尽可能节约内存的情况下支持读写百M的Excel

easyexcel官网

  • 导入依赖
    <!--EasyExcel相关依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.0.5</version>
        </dependency>
  • 编写Excl数据实体类

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.util.Date;

/**
 * @Description: 登记信息
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RegistrationInformation {

    private String ID;
    @ExcelProperty(value ="客户") // @ExcelProperty 注解的作用在于 映射excl的表头和实体类的字段关系
    private String ownerName;
    @ExcelProperty(value ="电话")
    private String contactNumber;
    @ExcelProperty(value ="身份证")
    private String idNumber;
    @ExcelProperty(value ="地址")
    private String address;
    @ExcelProperty(value ="品牌")
    private String brandAndModel;
    @ExcelProperty(value ="车牌")
    private String licensePlateNumber;
    @ExcelProperty(value ="车架号")
    private String frameNo;
    @ExcelProperty(value ="发动机")
    private String engineNumber;
    @JsonFormat(pattern = "yyyy-MM-dd HH:MM:ss", timezone = "GMT+8")
    @ExcelProperty(value ="登记时间")
    @DateTimeFormat("yyyy-MM-dd HH:mm:ss") //格式化Excl 的时间格式
    private Date createTime;
    @JsonFormat(pattern = "yyyy-MM-dd HH:MM:ss", timezone = "GMT+8")
    @ExcelProperty(value ="上次修改时间")
    @DateTimeFormat("yyyy-MM-dd HH:mm:ss")
    private Date updateTime;

}

注:
@ExcelProperty: 用于匹配excel和实体类的匹配
参数如下:

名称默认值描述
value用于匹配excel中的头,必须全匹配,如果有多行头,会匹配最后一行头
orderInteger.MAX_VALUE优先级高于value,会根据order的顺序来匹配实体和excel中数据的顺序
index-1优先级高于value和order,会根据index直接指定到excel中具体的哪一列
converter自动选择指定当前字段用什么转换器,默认会自动选择。读的情况下只要实现com.alibaba.excel.converters.Converter#convertToJavaData(com.alibaba.excel.converters.ReadConverterContext<?>) 方法即可

@DateTimeFormat: 日期转换,用String去接收excel日期格式的数据会调用这个注解
参数如下:

名称默认值描述
value参照java.text.SimpleDateFormat书写即可
use1904windowing自动选择excel中时间是存储1900年起的一个双精度浮点数,但是有时候默认开始日期是1904,所以设置这个值改成默认1904年开始

其他注解请参见官网

  • 导入,导出

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.example.vehicleinformationsystem.bean.RegistrationInformation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @Description:
 */
@RestController
@RequestMapping("/test")
public class test {
    /**
     * 操作数据库,mapper
     */
    @Autowired
    TestMapper mapper;
    /**
     * 导出excel
     * @param response
     * @return
     */
    @GetMapping("/download")
    public String  download(HttpServletResponse response){
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        try {

            //数据库将结果查询出来
            List<RegistrationInformation> infoList = mapper.selectList(null);

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
			//设置导出的文件名称及编码格式
            String fileName = URLEncoder.encode("车辆信息", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            EasyExcel.write(response.getOutputStream(), RegistrationInformation.class)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())//自适应表格格式
                    .sheet("模板")
                    .doWrite(infoList);
        } catch (IOException e) {
            e.printStackTrace();
            return  "程序异常"+e.getMessage();
        }
        return null;
    }

    /**
     * 导入excel
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file)  {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            List<RegistrationInformation> dataList = EasyExcel.read(inputStream).head(RegistrationInformation.class).sheet().doReadSync();
            inputStream.close();

            for (RegistrationInformation info:dataList ) {
                //将结果插入到数据库
               mapper.insert(info);
            }
        } catch (IOException e) {
            e.printStackTrace();

        }
        return"上传成功";
    }

}

  • EXCL格式
    在这里插入图片描述
  • 前端接收返回的二进制流excel表格文件
    参考博客
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

亿只王菜菜

各位爷,赏口饭吃吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值