Hutool Java 工具类库Excel导入,很方便!


前言

一、Hutool是什么?

Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让Java语言也可以“甜甜的”。

Hutool中的工具方法来自每个用户的精雕细琢,它涵盖了Java开发底层代码中的方方面面,它既是大型项目开发中解决小问题的利器,也是小型项目中的效率担当;

Hutool是项目中“util”包友好的替代,它节省了开发人员对项目中公用类和公用工具方法的封装时间,使开发专注于业务,同时可以最大限度的避免封装不完善带来的bug。

二、使用步骤

1.引入maven依赖

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.6.5</version>
</dependency>

2.Excel导入

  1. 1、 实体类
package com.example.demo.model;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * @author LL
 * @description : 用户信息
 * @date 2021/02/25 14:59
 */

@Data
@ApiModel(description = "用户信息")
public class User {

    @ApiModelProperty(notes = "id")
    private Integer id;

    @ApiModelProperty(notes = "姓名")
    private String name;

    @ApiModelProperty(notes = "年龄")
    private Integer age;

}
  1. 2、controller层
package com.example.demo.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @author LL
 * @description : 用户管理模块
 * @date 2021/02/25 15:38
 */

@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
@Api(value = "user", tags = "用户管理模块")
public class UserController {

    private final UserService userService;

    @ApiOperation(value = "导入用户信息", notes = "导入用户信息")
    @PostMapping("/import")
    public ResponseEntity<String> importExcel(@RequestParam("file") MultipartFile file) {
        try (InputStream inputStream = file.getInputStream()) {
            String[] excelHead = {"姓名", "年龄"};
            String[] excelHeadAlias = {"name", "age"};
            List<User> userList = importExcel(inputStream, excelHead, excelHeadAlias, User.class);
            if (ObjectUtil.isEmpty(userList)) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("导入模版不正确或数据为空");
            }
            userService.importUser(userList);
            return ResponseEntity.ok().body("导入成功");
        } catch (Exception ignored) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("导入失败");
        }
    }

    /**
     * 读取excel表格内容返回List<Bean>
     *
     * @param inputStream excel文件流
     * @param head        表头数组
     * @param headerAlias 表头别名数组
     * @return <T>List<T>
     */
    public static <T> List<T> importExcel(InputStream inputStream, String[] head, String[] headerAlias, Class<T> bean) {
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 多个sheet可以指定名称读取
        //ExcelReader reader = ExcelUtil.getReader(inputStream, "全部人员信息");
        List<Object> header = reader.readRow(0);
        // 替换表头关键字
        if (ArrayUtils.isEmpty(head) || ArrayUtils.isEmpty(headerAlias) || head.length != headerAlias.length) {
            return null;
        } else {
            for (int i = 0; i < head.length; i++) {
                if (head[i].equals(header.get(i))) {
                    reader.addHeaderAlias(head[i], headerAlias[i]);
                } else {
                    return null;
                }
            }
        }
        //读取指点行开始的表数据(从0开始)
        return reader.read(0, 0, bean);
    }
}

  1. 3、 service层
package com.example.demo.service;

import com.example.demo.model.User;

import java.util.List;

/**
 * @author LL
 * @description : 用户管理
 * @date 2021/02/25 15:54
 */
public interface UserService {

    /**
     * 导入用户信息
     * @param userList 用户信息List
     */
    void importUser(List<User> userList);
}
package com.example.demo.service;

import com.example.demo.dao.UserMapper;
import com.example.demo.model.User;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author LL
 * @description :
 * @date 2021/02/25 16:11
 */

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Override
    public void importUser(List<User> userList) {
        userMapper.insertUserList(userList);
    }
}
  1. 4、dao层
package com.example.demo.dao;

import com.example.demo.model.User;

import java.util.List;

/**
 * @author LL
 * @description : 用户管理
 * @date 2021/02/25 16:13
 */
public interface UserMapper {

    /**
     * 导入用户信息
     *
     * @param userList 用户信息List
     */
    void insertUserList(List<User> userList);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.dao.UserMapper">
	
	<sql id="TableName">
		tbl_user
	</sql>
	
	<insert id="insertUserList">
		INSERT INTO
			<include refid="TableName"/>
			(id, name, age)
		VALUES
			<foreach collection="userList" item="user" index="index" separator=",">
				(#{user.id,jdbcType=INTEGER}, #{user.name,jdbcType=VARCHAR}, #{user.age,jdbcType=INTEGER})
			</foreach>
	</insert>
	
</mapper>
  1. 5、数据库
/*
Navicat Premium Data Transfer

Source Server         : mysql
Source Server Type    : MySQL
Source Server Version : 50731
Source Host           : localhost:3306
Source Schema         : demo

Target Server Type    : MySQL
Target Server Version : 50731
File Encoding         : 65001

Date: 25/02/2021 15:21:29
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for tbl_user
-- ----------------------------
DROP TABLE IF EXISTS `tbl_user`;
CREATE TABLE `tbl_user`  (
 `id` int(11) NOT NULL,
 `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '姓名',
 `age` int(11) NULL DEFAULT NULL COMMENT '年龄',
 PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户表' ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of tbl_user
-- ----------------------------
INSERT INTO `tbl_user` VALUES (1, '张三', 20);
INSERT INTO `tbl_user` VALUES (2, '李四', 25);

SET FOREIGN_KEY_CHECKS = 1;

总结

如遇到问题,欢迎留言,我会及时回复!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值