easypoi实现Excel文件导入导出

使用easypoi做导入导出功能

1. 引入依赖


    cn.afterturn
    easypoi-base
    4.1.0


    cn.afterturn
    easypoi-web
    4.1.0


    cn.afterturn
    easypoi-annotation
    4.1.0

2.在pojo类上使用注解

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
@Data
@ExcelTarget("LitemallstoneMian")
public class LitemallStoneMain implements Serializable {

    public static final Boolean NOT_DELETED = false;

    public static final Boolean IS_DELETED = true;

    @TableId(value = "id", type = IdType.ID_WORKER_STR)
    private Integer id;

    @Excel(name = "入库编号",height = 20,width = 22,isImportField = "true_st")
    private String code;

    @Excel(name = "仓库ID",height = 20,width = 20,isImportField = "true_st")
    private Integer warehouseId;

    @Excel(name = "商户ID",height = 20,width = 20,isImportField = "true_st")
    private Integer bid;

    @Excel(name = "主石名称",height = 20,width = 20,isImportField = "true_st")
    private String name;

    @Excel(name = "主石类型",height = 20,width = 20,isImportField = "true_st")
    private String category;

    @Excel(name = "主石等级",height = 20,width = 20,isImportField = "true_st")
    private String grading;

    @Excel(name = "主石重量",height = 20,width = 20,isImportField = "true_st")
    private String carat;

    @Excel(name = "主石颜色",height = 20,width = 20,isImportField = "true_st")
    private String colour;

    @Excel(name = "主石净度",height = 20,width = 20,isImportField = "true_st")
    private String clarity;

    @Excel(name = "主石切工",height = 20,width = 20,isImportField = "true_st")
    private String cut;

    @Excel(name = "主石形状",height = 20,width = 20,isImportField = "true_st")
    private String shape;

    @Excel(name = "主石抛光",height = 20,width = 20,isImportField = "true_st")
    private String polishing;

    @Excel(name = "主石对称",height = 20,width = 20,isImportField = "true_st")
    private String symmetry;

    @Excel(name = "主石荧光",height = 20,width = 20,isImportField = "true_st")
    private String flourescence;

    @Excel(name = "主石证书类型",height = 20,width = 20,isImportField = "true_st")
    private String certificateType;

    @Excel(name = "主石证书编号",height = 20,width = 20,isImportField = "true_st")
    private String certificateCode;

    @Excel(name = "成本价",height = 20,width = 20,isImportField = "true_st")
    private String cost;

    @Excel(name = "条形码",height = 20,width = 20,isImportField = "true_st")
    private String barCode;

    @Excel(name = "创建时间",databaseFormat = "yyyyMMddHHmmss",format = "yyyy-MM-dd",width = 20)
    private Date addTime;

    @Excel(name = "更新时间",databaseFormat = "yyyyMMddHHmmss" ,format = "yyyy-MM-dd",width = 20)
    private Date updateTime;

    @ApiModelProperty(value = "状态,0正常,1上架,2下架,3锁定,4盘点,5已售")
    private Integer status;

    //该属性是为了实现该status值呈现中文状态
    @Excel(name = "状态",height = 20,width = 20,isImportField = "true_st")
    private String statuses;

    private Boolean deleted;

    public void andLogicalDeleted(boolean deleted) {
        setDeleted(deleted ? IS_DELETED : NOT_DELETED);
    }

    public LitemallStoneMain() {
    }

    public LitemallStoneMain(Integer warehouseId, Integer bid,
                             String code, String name, String category) {
        this.warehouseId = warehouseId;
        this.bid = bid;
        this.code = code;
        this.name = name;
        this.category = category;
    }
}

@Excel注解是用在你需要导入导出的字段名上,具体的字段使用方法介绍可以浏览easypoi开源文档。

@Data这个注解是lombok的,这里不在做过多赘述,这里的目的是自动生成get和set方法。

这里要注意的是一定要把无参构造和有参构造方法都写出来,因为后面在导入的时候需要用到,有参构造方法只需要生成你加了@Excel注解的字段即可。

3.dao层方法

@Mapper
public interface LitemallStoneMainMapper{

//批量插入
Integer batchInsert(List stoneMainList);

}

因为后面要做导入操作,所以这里的方法是批量插入方法。

4.Mapper.xml中SQL语句


    INSERT INTO litemall_stone_main(warehouse_id,bid,code,`name`,category,grading,carat,
                                    colour,clarity,cut,shape,polishing,symmetry,flourescence,
                                    certificate_type,certificate_code,cost,bar_code,add_time,
                                    update_time,status)
    VALUES 
    
        (#{stoneMain.warehouseId,jdbcType=INTEGER},#{stoneMain.bid,jdbcType=INTEGER},#{stoneMain.code,jdbcType=VARCHAR},
        #{stoneMain.name,jdbcType=VARCHAR},#{stoneMain.category,jdbcType=VARCHAR},#{stoneMain.grading,jdbcType=VARCHAR},
        #{stoneMain.carat,jdbcType=VARCHAR},#{stoneMain.colour,jdbcType=VARCHAR},#{stoneMain.clarity,jdbcType=VARCHAR},
        #{stoneMain.cut,jdbcType=VARCHAR},#{stoneMain.shape,jdbcType=VARCHAR},#{stoneMain.polishing,jdbcType=VARCHAR},
        #{stoneMain.symmetry,jdbcType=VARCHAR},#{stoneMain.flourescence,jdbcType=VARCHAR},#{stoneMain.certificateType,jdbcType=VARCHAR},
        #{stoneMain.certificateCode,jdbcType=VARCHAR},#{stoneMain.cost,jdbcType=VARCHAR},#{stoneMain.barCode,jdbcType=VARCHAR},
        #{stoneMain.addTime,jdbcType=TIMESTAMP},#{stoneMain.updateTime,jdbcType=TIMESTAMP},#{stoneMain.status,jdbcType=INTEGER})
    

5.service层

因为这个项目是使用分布式来写的,所以会有一个japp和jweb2个模块,所以就存在2个service层。这里简单说一下2个模块的用处:japp是用来做数据库的操作,jweb层是不涉及到数据库的操作的

japp模块service层方法

//批量插入
public Integer batchInsert(List stoneMainList) {
    for (LitemallStoneMain stoneMain : stoneMainList) {
        String statuses=stoneMain.getStatuses();
        //通过时间戳+6位随机数生成入库编号(code)
        int r = (int) ((Math.random() * 9 + 1) * 100000);
        String num = String.valueOf(r);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(new Date());
        String code = date + num;
        stoneMain.setCode(code);
        stoneMain.setAddTime(new Date());
        stoneMain.setUpdateTime(new Date());

        //0正常,1上架,2下架,3锁定,4盘点,5已售
        switch (statuses){
            case "正常":
                stoneMain.setStatus(0);
                break;
            case "上架":
                stoneMain.setStatus(1);
                break;
            case "下架":
                stoneMain.setStatus(2);
                break;
            case "锁定":
                stoneMain.setStatus(3);
                break;
            case "盘点":
                stoneMain.setStatus(4);
                break;
            case "已售":
                stoneMain.setStatus(5);
                break;
            default:
                break;
        }
    }
    return stoneMainMapper.batchInsert(stoneMainList);
}

这只是生成时间戳和6位随机数生成入库编号的方法,用不到可以忽略不计哈…

jweb模块service层中方法

//批量插入
public Integer batchInsert(List stoneMainList) {
    try {

        ResultVO resultVO=null;
        //mysql不要一次性插入超过999条数据
        if (stoneMainList.size() > 999) {
            //分批次插入
            Integer count = stoneMainList.size() / 999;

            //分批次插入的集合
            List subList = new ArrayList<>();

            for (Integer i = 1; i <= count; i++) {
                //截取list集合 0-999
                subList.add(stoneMainList.subList((i - 1) * 999, i * 999));
                if (i == count && stoneMainList.size() % 999 != 0) {
                    //有999的余数
                    subList.add(stoneMainList.subList(i * 999, stoneMainList.size() - 1));
                }
            }

            //分批次插入
            for (List list : subList) {
                 resultVO = stoneMainClient.batchInsert(list);
            }
            return (Integer) resultVO.getData();
        } else {
            resultVO = stoneMainClient.batchInsert(stoneMainList);
            return (Integer) resultVO.getData();
        }


    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

ResultVO是我们自己封装的一个类,所以ResultVO result=null;可以改成Integer result=0;

5.Controller层

这里的的controller层是jweb层,也就是最终对接前端接口的前端控制层

@RestController
@RequestMapping("/admin/stoneMain/")
public class AdminStoneMainController {

    @Autowired
    private LitemallStoneMainService stoneMainService;

    Logger log=     LoggerFactory.getLogger(AdminStoneMainController.clas    s);

    /**
     * 通过easypoi导出excel(下载)
     *
     * @param response
     */
    @RequestMapping("export")
    @ApiOperation(value = "导出excel", httpMethod =     "GET")
    public void excelExport(HttpServletResponse response) {
        try {
            // 设置响应输出的头类型
            response.setHeader("content-Type",     "application/vnd.ms-excel");
            // 下载文件的默认名称
            response.setHeader("Content-Disposition",    "attachment;filename=stoneMain.xls");
            // =========easypoi部分
            ExportParams exportParams = new     ExportParams("主石库存表","主石库存");
            // exportParams.setDataHanlder(null);//和导入    一样可以设置一个handler来处理特殊数据
            Workbook workbook =     ExcelExportUtil.exportExcel(exportParams,     LitemallStoneMain.class, data());
            workbook.write(response.getOutputStream());
            response.getOutputStream().close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
    private List data() {
        List list =     stoneMainService.queryList();
        for (LitemallStoneMain stoneMain : list) {
            Integer status = stoneMain.getStatus();
            //0正常,1上架,2下架,3锁定,4盘点,5已售
            switch (status){
                case 0:
                    stoneMain.setStatuses("正常");
                    break;
                case 1:
                    stoneMain.setStatuses("上架");
                    break;
                case 2:
                    stoneMain.setStatuses("下架");
                    break;
                case 3:
                    stoneMain.setStatuses("锁定");
                    break;
                case 4:
                    stoneMain.setStatuses("盘点");
                    break;
                case 5:
                    stoneMain.setStatuses("已售");
                    break;
                default:
                    break;
            }
        }
        return list;
    }
    
    /**
     * 导入excel
     *
     * @param file
     */
    @RequestMapping("import")
    @PostMapping(value = "/", headers =     "content-type=multipart/form-data")
    @ApiOperation(value = "导入excel", httpMethod =     "POST")
    public void excelImport(HttpServletRequest request,     MultipartFile file) {
        System.out.println("导入开始--->");
        System.out.println("file--->" + file);

        //构建解析execl的easypoi参数
        ImportParams params = new ImportParams();
        params.setTitleRows(1); //标题行
        params.setHeadRows(1);  //别名

        try {

            //读取数据
            List list =     ExcelImportUtil.importExcel(file.getInputStre    am(), LitemallStoneMain.class, params);

            //设置对象默认值
            for (LitemallStoneMain stoneMain : list) {
                System.out.println(stoneMain.toString());
            }

            Integer result =     stoneMainService.batchInsert(list);
            if (result > 0) {
                System.out.println("导入成功");
            } else {
                System.out.println("导入失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}

我把导入方法和导出方法写到一起,只是为了方便大家看,因为一般做了导出操作,肯定会做导入操作,其中导出操作方法是直接下载导出到本地,不是那种直接保存到本地,如果项目存在上线的可能,那么保存到本地实际上市保存到服务器上的,在本地是看不到,所以直接把导出文件下载到本地是比较方便的。

导出方法就比较简单的,很容易看明白。

在这里我没有去做验证操作,因为项目上线之后,只可能会在初期存在导入操作,中后期基本不存在导入操作,所以就没有加验证的方法

你可能感兴趣的:(easyPoi,easypoi,导入导出Excel)