导入Excel表格批量增加

导入Excel表格批量增加

直接上代码

<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml</artifactId>
   <version>4.1.2</version>
</dependency>
package com.ruoyi.juancloud.videocloudbroadcasting.util;

import com.github.pagehelper.util.StringUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;

import static org.apache.poi.ss.usermodel.CellType.STRING;

/**
 * @Author: yang
 * @Description: Excel导入工具类
 * @Date: 2022/07/16 10:54
 * @Version: 1.0
 */
public class ReadExcelByPoi<T> {

    private static final String XLS = "xls";
    private static final String XLSX = "xlsx";

    /**
     * 泛型类,T:虚拟类型;
     *
     * @param t        转化类型
     * @param filePath 上传文件
     * @return
     */
    public List<T> readExcelByPoi(T t, MultipartFile filePath) {
        //创建一个对应的空的泛型集合
        List<T> infoList = new ArrayList<>();
        // 反射出类类型(方便后续做操作)
        Class c = t.getClass();
        // 获得该类所有自己声明的字段,包括该类中继承 Serializable 的UID
        Field[] fs = c.getDeclaredFields();
        //map集合是存读取到的excel行数据
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        try {
            //获取到页面传递过来文件的文件名截取后缀
            int index = Objects.requireNonNull(filePath.getOriginalFilename()).lastIndexOf(".");
            String postfix = filePath.getOriginalFilename().substring(index + 1);
            Workbook workbook = null;
            //根据后缀判断使用 hssf或 xssf
            if (XLS.equals(postfix)) {
                workbook = new HSSFWorkbook(filePath.getInputStream());
            } else if (XLSX.equals(postfix)) {
                workbook = new XSSFWorkbook(filePath.getInputStream());
            }
            //获取Excel表中的数据开始,默认只有sheet1 一页数据 存入map↓-------------------
            assert workbook != null;
            Sheet sheet = workbook.getSheetAt(0);
            //总的行数
            int rows = sheet.getLastRowNum();
            //总的列数--->最后一列为null则有问题,读取不完整,将表头的数目作为总的列数,没有的则补为null
            int columns = sheet.getRow(0).getLastCellNum();
            //先列后行
            for (int i = 1; i <= rows; i++) {
                Row row = sheet.getRow(i);
                //这一行是空行,不读取
                if (null != row && row.getFirstCellNum() == -1) {
                    continue;
                }
                List<String> contentList = new ArrayList<String>();
                for (int j = 0; j < columns; j++) {
                    assert row != null;
                    if (row.getCell(j) != null) {
                        row.getCell(j).setCellType(STRING);
                        contentList.add(row.getCell(j).getStringCellValue());
                    } else {
                        contentList.add("");
                    }
                }
                map.put("entityInfo" + i, contentList);
            }
            //获取Excel表中的数据结束,默认只有sheet1 一页数据 ↑-------------------
            //遍历map集合,封装成bean
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                t = (T) c.newInstance();
                List<String> list = entry.getValue();
                //fs.length 是你传入实体类的所有字段个数,包括该类中继承 Serializable 的UID
                //所以这里最后比对一下,将长度判断相等,或者去除Excel中没有的字段
                //这里我将Serializable 的UID 去除,所以 i 从1开始;
                for (int i = 1; i < fs.length; i++) {
                    //fs[i].getName():获得字段名 f:获得的字段信息
                    Field f = t.getClass().getDeclaredField(fs[i].getName());
                    // 参数true 可跨越访问权限进行操作
                    f.setAccessible(true);
                    // 判断其类型进行赋值操作
                    if (f.getType().getName().equals(String.class.getName())) {
                        //因为i从1开始,然后list的角标需要从0开始,所以这里减去1,保障不会角标越界;
                        //注意:excel模板中的列数是和实体类的字段对应排列的
                        if (StringUtil.isEmpty(list.get(i - 1))) {
                            f.set(t, null);
                        } else {
                            f.set(t, list.get(i - 1));
                        }
                    } else if (f.getType().getName().equals(Integer.class.getName())) {
                        if (StringUtil.isEmpty(list.get(i - 1))) {
                            f.set(t, null);
                        } else {
                            f.set(t, Integer.parseInt(list.get(i - 1)));
                        }
                    } else if (f.getType().getName().equals(Long.class.getName())) {
                        if (StringUtil.isEmpty(list.get(i - 1))) {
                            f.set(t, null);
                        } else {
                            f.set(t, Long.valueOf(list.get(i - 1)));
                        }
                    } else if (f.getType().getName().equals(BigDecimal.class.getName())) {
                        BigDecimal bigDecimal = new BigDecimal(list.get(i - 1));
                        if (StringUtil.isEmpty(list.get(i - 1))) {
                            f.set(t, bigDecimal);
                        } else {
                            f.set(t, bigDecimal);
                        }
                    }
                }
                //将完整的实体存入集合返回;接收到后只需要循环调用insert方法即可
                infoList.add(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return infoList;
    }
}

控制层

    @PostMapping("/importExcel")
    public AjaxResult getPathToExcel(@RequestParam("uploadFile") MultipartFile file,
                                     @RequestPart @Validated String groupId) {
        //创建readExcelByPOI工具类,泛型为导入的实体类
        ReadExcelByPoi<Device> readExcelByPoi = new ReadExcelByPoi<>();
        //传入导入的实体类,以及文件
        List<Device> startContents = readExcelByPoi.readExcelByPoi(new Device(), file);
        ArrayList<Device> list = new ArrayList<>();
        for (Device device : startContents) {
            //校验code唯一
            Device dev = new Device();
            dev.setDeviceCode(device.getDeviceCode());
            List<Device> devices = deviceService.selectDeviceList(dev);
            //大于零表示code已经存在
            if (devices.size() > 0) {
                return AjaxResult.error("设备id重复!重复id为:" + device.getDeviceCode());
            }
            list.add(device);
        }
        //做一个简单的判断,然后进行写入
        if (startContents.size() > 0) {
            try {
                tblFixChangeServiceImpl.getGroupDevice(list, Long.valueOf(groupId));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return AjaxResult.success("添加成功!");
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值