layUI+EasyPoi实现基本的表格导入

EasyPoi + layerUI 实现基本的表格导入

1、在pom文件中引入EasyPoi的坐标依赖:
注意:如果各项目间存在父子项目依赖关系,该POI坐标依赖应配置在父项目的pom.xml文件中
		   <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>
2、创建项目数据表
CREATE TABLE `led_generation_records` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `create_user` bigint(20) DEFAULT NULL COMMENT '创建人',
  `update_time` datetime DEFAULT NULL COMMENT '修改时间',
  `update_user` bigint(20) DEFAULT NULL COMMENT '修改人',
  `del` varchar(255) DEFAULT NULL COMMENT '软删除',
  `version` bigint(20) DEFAULT NULL COMMENT '版本',
  `type` varchar(255) DEFAULT NULL COMMENT '类型',
  `sort` bigint(20) DEFAULT NULL COMMENT '排序',
  `description` text COMMENT '描述',
  `generation` varchar(255) DEFAULT NULL COMMENT '发电量',
  `statistics` varchar(255) DEFAULT NULL COMMENT '统计',
  `year` int(6) DEFAULT NULL COMMENT '年',
  `month` int(6) DEFAULT NULL COMMENT '月',
  `day` int(6) DEFAULT NULL COMMENT '日',
  `dept_name` varchar(255) DEFAULT NULL COMMENT '组织机构',
  `dept_id` bigint(20) DEFAULT NULL COMMENT '组织机构id',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2332 DEFAULT CHARSET=utf8 COMMENT='历年发电记录';
3、根据表创建对应的实体类,此处采用lombok注解@Data来替代类中各属性的get/set方法,使用@ExcelTarget(" ")来指定该表格的唯一标识,通过@Excel(name = “发电量”)指定需要导入、导出表格的列头名称。
注意:表格的导入导出涉及到数据流传输,因此一定要让该实体类实现序列化接口***Serializable***
/**
 * <p>
 * 历年发电记录
 * </p>
 *
 * @author Orange
 * @since 2020-11-22
 */
@Data
@TableName("led_generation_records")
@ExcelTarget("history")
public class LedGenerationRecords implements Serializable {

    private static final long serialVersionUID=1L;

    /**
     * 主键
     */
      @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 创建时间
     */
      @TableField(value = "create_time", fill = FieldFill.INSERT)
    private Date createTime;

    /**
     * 创建人
     */
    @TableField(value = "create_user", fill = FieldFill.INSERT)
    private Long createUser;

    /**
     * 修改时间
     */
    @TableField(value = "update_time", fill = FieldFill.UPDATE)
    private Date updateTime;

    /**
     * 修改人
     */
    @TableField(value = "update_user", fill = FieldFill.UPDATE)
    private Long updateUser;

    /**
     * 软删除
     */
    @TableField("del")
    private String del;

    /**
     * 版本
     */
    @TableField("version")
    private Long version;

    /**
     * 类型
     */
    @TableField("type")
    private String type;

    /**
     * 排序
     */
    @TableField("sort")
    private Long sort;

    /**
     * 描述
     */
    @TableField("description")
    private String description;

    /**
     * 发电量
     */
    @Excel(name = "发电量")
    @TableField("generation")
    private String generation;

    /**
     * 统计
     */
    @TableField("statistics")
    private String statistics;

    /**
     * 年
     */
    @Excel(name = "年")
    @TableField("year")
    private Integer year;

    /**
     * 月
     */
    @Excel(name = "月")
    @TableField("month")
    private Integer month;

    /**
     * 日
     */
    @Excel(name = "日")
    @TableField("day")
    private Integer day;

    /**
     * 组织机构
     */
    @Excel(name = "组织机构")
    @TableField("dept_name")
    private String deptName;

    /**
     * 组织机构id
     */
    @Excel(name = "组织id")
    @TableField("dept_id")
    private Long deptId;
4、可通过测试方法导出数据表格作为表格导入模板
    @Test
    public void ExportExcel() throws IOException {

        List<LedGenerationRecords> ledGenerationRecordsList = new ArrayList<>();

        //此处模拟五条数据
        for(int i=0;i<5;i++){
            LedGenerationRecords ledGenerationRecords = new LedGenerationRecords();
            ledGenerationRecords.setGeneration("100");
            ledGenerationRecords.setYear(2020);
            ledGenerationRecords.setMonth(11);
            ledGenerationRecords.setDay(12);
            ledGenerationRecords.setDeptId(25l);
            ledGenerationRecords.setDeptName("测试电厂");
            ledGenerationRecordsList.add(ledGenerationRecords);
        }

        FileOutputStream fileOutputStream = new FileOutputStream("D:\\tmp/数据表格.xls");
        Workbook exportExcel = ExcelExportUtil.exportExcel(new ExportParams("历年数据导入", "数据表"), LedGenerationRecords.class, ledGenerationRecordsList);
        exportExcel.write(fileOutputStream);
        fileOutputStream.close();
        exportExcel.close();
    }
5、代码生成的模板表如下:

在这里插入图片描述

6、前台代码与JS
 <button id="btnImp" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>导入</button>
//初始化
var upload = layui.upload;
//指定允许上传的文件类型
    upload.render({
        elem: '#btnImp' //id对应
        ,url: Feng.ctxPath +'/ledGenerationRecords/importExcel' //文件上传接口
        ,accept: 'file' //普通文件
        ,exts: 'xls|xlsx' //只允许上传文件格式
        ,done: function(res){
            table.reload(LedGenerationRecords.tableId, {url: Feng.ctxPath + "/ledGenerationRecords/insertData"});//数据存储接口
            //延时刷新
            window.setTimeout(function () {
                window.location.reload();
            },800)

        }
    });
7、后台对应接口
    /**
    * @Description: 表格上传控制器
    * @author: Orange
    * @Param:
    * @Return:
    * @Date: 2020/12/5 11:33
    */
    @RequestMapping("/importExcel")
    @ResponseBody
    public ResponseData uploadExcel(@RequestPart("file") MultipartFile file, HttpServletRequest request) throws IOException {
        JSONObject result = new JSONObject();
        //获得上传文件名
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        String fileNames = fileName + "." + ext;
        //将文件名存放在域中
        request.getSession().setAttribute("importFile", fileNames);
        //此行是所在项目所封装的方法,复制后不可用,作用是获得文件存储的盘符路径
        String fileParentPath = ConstantsContext.getBpmnFileUploadPath();
        String pathName = fileParentPath + fileNames;
        File importFile = new File(pathName);
        file.transferTo(importFile);
        result.put("result",pathName);
        return ResponseData.success(0, "上传成功", result);
    }

        /**
         * @Description: 读取表格控制器
         * @author: Orange
         * @Param:
         * @Return:
         * @Date: 2020/12/5 11:46
         */
        @RequestMapping("/insertData")
        @ResponseBody
        public String getUploadData(HttpServletRequest request) {
            //从域中获取文件名
            String name = (String) request.getSession().getAttribute("importFile");
            //获得文件存放地址
            String fileSavePath = ConstantsContext.getBpmnFileUploadPath();
            if (name != null) {
                File file = new File(fileSavePath + name);
                try {
                    ImportParams params = new ImportParams();
                    //读取表头 1行
                    params.setTitleRows(1);
                    //读取列头 1行
                    params.setHeadRows(1);
                    List result = ExcelImportUtil.importExcel(file, LedGenerationRecords.class, params);
                    //数据打印
                    result.forEach(System.out::println);
                    //调用保存数据的方法
                    ledGenerationRecordsService.saveExcel(result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //保存完成后重定向到数据列表界面
            return "redirect:/ledGenerationRecords";
        }
8、注意:因建表时设置主键策略为自动增长,所以在对应的xxxMapper.xml文件中的insert语句要设置对应的自动增长
 <insert id="saveExcel" parameterType="cn.stylefeng.guns.modular.led.entity.LedGenerationRecords" useGeneratedKeys="true" keyProperty="id">
        insert into  led_generation_records (id, generation ,year ,month ,day ,dept_name,dept_id) values (#{id},#{generation},#{year},#{month},#{day},#{deptName},#{deptId})
    </insert>

注:EasyPOi还有很多强大的表格格式设置功能并且很好上手,具体可以参考EasyPOI的官网

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值