JAVA表格数据导入到数据库(POI实现)

JAVA表格数据导入到数据库

前几天参加了个面试,笔试过程中有一个怎么把表格导入到数据库,我是知道把表格导入到数据库是可以使用POI的,也知道大概思路,不过确实以前项目中没有遇到过,今天正好有时间,手写一下如何将数据导入到数据库中,话不多说上代码。
首先我们既然使用poi就要导入相应的poi依赖

        <!--读取excel文件-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.10-FINAL</version>
        </dependency>

然后看一下目录结构(主要的已经标记上了)
在这里插入图片描述

首先先看一下Excel工具类(ExcelUtil)中的代码

public class ExcelUtil {
    private static final Log logger = LogFactory.getLog(ExcelUtil.class);
    private final static String xls = "xls";
    private final static String xlsx = "xlsx";

    /**
     * 解析文件成为list数组
     * @param file
     * @return
     * @throws IOException
     */
    public static List<String[]> readExcel(MultipartFile file) throws IOException {
        //判断是否为excel文件
        checkFile(file);
        //获得工作簿对象
        Workbook workbook=getWorkBook(file);
        //用于记录每一行的数据
        List<String[]> list=new ArrayList<>();
        //判断对象不为空
        if(workbook != null) {
            //循环工作簿对象的每一个sheet对象
            for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
                //获取当前工作表
                Sheet sheet = workbook.getSheetAt(sheetNum);
                //表为空去遍历下一个
                if(sheet == null){
                    continue;
                }
                //获取开始行数
                int firstRowNum = sheet.getFirstRowNum();
                //获取结尾行数
                int lastRowNum = sheet.getLastRowNum();
                //获取开始行
                Row firstRow = sheet.getRow(firstRowNum);
                //获取第一行开始列
                int firstCellNum = firstRow.getFirstCellNum();
                //获取最后一列
                int lastCellNum = firstRow.getLastCellNum();
                //遍历除了第一行的每一行
                for(int rowNum = firstRowNum+1; rowNum <= lastRowNum;rowNum++){
                    Row row = sheet.getRow(rowNum);
                    if(row == null){
                        continue;
                    }
                    String[] cells = new String[lastCellNum];
                    //遍历当前行的每一列
                    for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){
                        //得到当前列
                        Cell cell = row.getCell(cellNum);
                        //解析当前列的数据得到字符串
                        cells[cellNum] = getCellValue(cell);
                    }
                    list.add(cells);
                }
            }
        }
        return list;
    }

    /**
     * 判断文件是否合格
     * @param file
     * @throws IOException
     */
    public static void checkFile(MultipartFile file) throws IOException {
        if(file==null){
            throw new FileNotFoundException("文件不存在");
        }

        String filename = file.getOriginalFilename();

        if(!filename.endsWith(xls) && !filename.endsWith(xlsx)){
            throw new IOException("文件不是excel文件");
        }
    }

    /**
     * 得到Excel的工作簿
     * @param file
     * @return
     */
    public static Workbook getWorkBook(MultipartFile file) {
        //得到文件名
        String fileName = file.getOriginalFilename();
        //获得工作簿对象
        Workbook workbook = null;
        try {
            InputStream is = file.getInputStream();
            if(fileName.endsWith(xls)){
                workbook = new HSSFWorkbook(is);
            }else if(fileName.endsWith(xlsx)){
                workbook = new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            logger.info(e.getMessage());
        }
        return workbook;
    }

    /**
     * 解析每一列的数据成string
     * @param cell
     * @return
     */
    public static String getCellValue(Cell cell){
        String cellValue = "";
        if(cell == null){
            return cellValue;
        }
        //把数字当成String来读,避免出现1读成1.0的情况
        if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }
        //判断数据的类型
        switch (cell.getCellType()){
            case Cell.CELL_TYPE_NUMERIC: //数字
                cellValue = String.valueOf(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING: //字符串
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN: //Boolean
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA: //公式
//                cellValue = String.valueOf(cell.getCellFormula());
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_BLANK: //空值
                cellValue = "";
                break;
            case Cell.CELL_TYPE_ERROR: //故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }
}

注释也比较清楚,这个主要就是解析文件,获得每一行每一列的数据返回一个list
其实在这里有一个问题就是当你解析xlsx文件的时候就是这句代码

workbook = new XSSFWorkbook(is);

它是有问题的,我们还要导入对应的依赖

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.14</version>
        </dependency>

接下来看一下service层的代码

@Slf4j
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, User> implements IAdminService {

    @Override
    public List<User> upExcel(MultipartFile multipartFile) {
        List<User> users = new ArrayList<User>();
        try {
            List<String[]> list = ExcelUtil.readExcel(multipartFile);
            if(list!=null && list.size()>0){
                for(int i=0; i<list.size(); i++){
                    User user = new User();
                    if(list.get(i)[0]!=null&&list.get(i)[0]!=""){
                        for(int j=0; j<list.get(i).length; j++){
                            switch (i) {
                                case 0:{
                                    //姓名
                                    if (list.get(i)[j] != null && !list.get(i)[j].equals("")) {
                                        user.setUsername(list.get(i)[j]);
                                    }
                                    break;
                                }
                                case 1:{
                                    //性别
                                    if (list.get(i)[j] != null && !list.get(i)[j].equals("")) {
                                        user.setSex(list.get(i)[j]);
                                    }
                                    break;
                                }
                                case 2:{
                                    //手机号
                                    if (list.get(i)[j] != null && !list.get(i)[j].equals("")) {
                                        user.setPhone(list.get(i)[j]);
                                    }
                                    break;
                                }
                                case 3:{
                                    //电子邮箱
                                    if (list.get(i)[j] != null && !list.get(i)[j].equals("")) {
                                        user.setEmail(list.get(i)[j]);
                                    }
                                    break;
                                }
                                case 4:{
                                    //身份
                                    if(list.get(i)[j]!=null && !list.get(i).equals("")){
                                        user.setStatus(list.get(i)[j]);
                                    }
                                    break;
                                }
                                case 5:{
                                    //薪资
                                    if(list.get(i)[j] != null && !list.get(i)[j].equals("")){
                                        user.setMoney(list.get(i)[j]);
                                    }
                                    break;
                                }
                                default:{
                                    break;
                                }
                            }
                        }
                    }
                    users.add(user);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return users;
    }

这个主要就是拿到了list我们去按照顺序吧数据都放到user对象中,这个按照自己的需求去改就好。之后只需要使用controller层·去调用的到一个list的集合,直接使用批量插入就好。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值