springboot实现将excel数据导入数据库


前言

提示:这里可以添加本文要记录的大概内容:

springboot实现excel数据导入到数据库


提示:以下是本篇文章正文内容,下面案例可供参考

一、使用步骤

maven

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.1</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.1</version>
        </dependency>

1.实体类代码



import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * @author zhangdong
 * @version 1.0
 * @date 2022/5/30 16:34
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class WxAuthPersonnelInfo {
    //主键
    private String id;
    //分公司
 private String branch;
   
    //注册时间
    private Date registertime;


}

代码如下(示例):

2.mapper代码


import com.suorui.wx.model.WxAuthPersonnelInfo;
import org.apache.ibatis.annotations.Mapper;

/**
 * @author zhangdong
 * @version 1.0
 * @date 2022/5/31 15:08
 */
@Mapper
public interface WxAuthPersonnelInfoDao {

    //将excel数据插入到数据库
    void addUser(WxAuthPersonnelInfo wxAuthPersonnelInfo);

}

xml文件

<?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.wx.dao.WxAuthPersonnelInfoDao">
    <insert id="addUser">
        insert into WX_AUTH_PERSONNEL_INFO
            (ID,BRANCH,REGISTERTIME)
        values(
               #{id,jdbcType=VARCHAR},
               #{BRANCH,jdbcType=VARCHAR}, 
               #{registertime,jdbcType=TIMESTAMP}
        )
    </insert>

</mapper>

service 代码


import com.suorui.wx.dao.WxAuthPersonnelInfoDao;
import com.suorui.wx.model.WxAuthPersonnelInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zhangdong
 * @version 1.0
 * @date 2022/5/30 20:53
 */
@Service
@Slf4j
public class WxAuthPersonnelInfoService {
    @Autowired
    private WxAuthPersonnelInfoDao wxAuthPersonnelInfoDao;
    @Autowired
    private EncryptPropUtil encryptPropUtil;
    public boolean batchImport(String fileName, MultipartFile file) throws Exception {

        boolean notNull = false;
        List<WxAuthPersonnelInfo> userList = new ArrayList<WxAuthPersonnelInfo>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
          throw   new RuntimeException("选择文件格式不正确,请下载模板上传");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;

        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        // 获取excel的sheet页数
        int numberOfSheets = wb.getNumberOfSheets();
        //获取excel字段名称进行比较
        Sheet sheetAt = wb.getSheetAt(0);
        Row row1 = sheetAt.getRow(1);
        String xuhao = row1.getCell(0).getStringCellValue();
        String fengongsi = row1.getCell(1).getStringCellValue();
        String suoshuxian = row1.getCell(2).getStringCellValue();
        String zhijumingcheng = row1.getCell(3).getStringCellValue();
        String wanggemingcheng = row1.getCell(4).getStringCellValue();
        String kehujingli = row1.getCell(5).getStringCellValue();
        String lianxidianhua = row1.getCell(6).getStringCellValue();
        String gonghao = row1.getCell(7).getStringCellValue();
        String shuoming = row1.getCell(8).getStringCellValue();

        if ("序号".equals(xuhao) && "分公司".equals(fengongsi) && "所属县".equals(suoshuxian)
                && "支局名称".equals(zhijumingcheng) && "网格名称".equals(wanggemingcheng)
                && "客户经理".equals(kehujingli) && "联系电话".equals(lianxidianhua)
                && "工号".equals(gonghao) && "说明".equals(shuoming)){
            log.info("格式正确");

        }else {
            throw new RuntimeException("表字段格式错误,请下载模板");
        }

        for (int i = 0; i < numberOfSheets; i++) {
            Sheet sheet = wb.getSheetAt(i);
            if(sheet!=null){
                notNull = true;
            }
            WxAuthPersonnelInfo wxAuthPersonnelInfo;
            // 循环行数
            for (int r = 2; r <= sheet.getLastRowNum(); r++) {
                // 获取sheet的第r行的数据
                Row row = sheet.getRow(r);
                if (row == null){
                    continue;
                }

                wxAuthPersonnelInfo = new WxAuthPersonnelInfo();
                String uuid = UuidUtil.getUuid();
                wxAuthPersonnelInfo.setId(uuid);
                wxAuthPersonnelInfo.setStaffType("10005");
                wxAuthPersonnelInfo.setStaffSign("用户至上,用心服务");
                wxAuthPersonnelInfo.setStaffSex("1");
                wxAuthPersonnelInfo.setAuthStatus("0");
                wxAuthPersonnelInfo.setRegistertime(new Date());



                String areaCode = row.getCell(1).getStringCellValue();
                wxAuthPersonnelInfo.setAreaCode(areaCode);

                String county = row.getCell(2).getStringCellValue();
                wxAuthPersonnelInfo.setCounty(county);

                String branchName = row.getCell(3).getStringCellValue();
                wxAuthPersonnelInfo.setBranchName(branchName);

                String gridName = row.getCell(4).getStringCellValue();
                wxAuthPersonnelInfo.setGridName(gridName);

                String account_manager = row.getCell(5).getStringCellValue();
                //姓名加密
                String name = encryptPropUtil.encrPublic3des(account_manager);
                wxAuthPersonnelInfo.setStaffName(name);

                Cell cell = row.getCell(6);
                cell.setCellType(CellType.STRING);
                String phoneNum = row.getCell(6).getStringCellValue();
                wxAuthPersonnelInfo.setPhonenum(phoneNum);

                Cell cell1 = row.getCell(7);
                cell1.setCellType(CellType.STRING);
                String staffCode = row.getCell(7).getStringCellValue();
                wxAuthPersonnelInfo.setStaffCode(staffCode);

                String remarks = row.getCell(8).getStringCellValue();
                wxAuthPersonnelInfo.setRemarks(remarks);

                userList.add(wxAuthPersonnelInfo);

            }
        }

        for (WxAuthPersonnelInfo userResord : userList) {
                //数据插入到数据库
                wxAuthPersonnelInfoDao.addUser(userResord);
                //控制台输出插入的数据
                System.out.println(" 插入 "+userResord);
        }
        System.out.println(" 插入了 "+userList.size()+"条数据");
        return notNull;
    }

}

controller


import com.suorui.wx.service.WxAuthPersonnelInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author zhangdong
 * @version 1.0
 * @date 2022/5/31 16:07
 */
@RestController
@RequestMapping("/excel")
@Slf4j
public class WxAuthPersonnelInfoController {
    @Autowired
   private WxAuthPersonnelInfoService wxAuthPersonnelInfoService;


    @GetMapping("/toexcel")
    public ModelAndView toexcel(){
        ModelAndView model = new ModelAndView();
        model.setViewName("/excel/upload");

        return model;
    }



    @PostMapping("/import")
    public CommRetVo addUser(@RequestParam("file") MultipartFile file) {
        CommRetVo commRetVo = new CommRetVo();
        boolean a = false;
        String fileName = file.getOriginalFilename();
        try {
            a = wxAuthPersonnelInfoService.batchImport(fileName, file);
            commRetVo.setCode("1");
            commRetVo.setMsg("成功");
        } catch (Exception e) {
            commRetVo.setCode("0");
            log.error("失败", e);
            log.info("{}",e.getMessage());
            String message = e.getMessage();
            commRetVo.setMsg(message);
        }
        return commRetVo;
    }
   


}


总结

实体类需要自己改
EncryptPropUtil 是公司封装的加密工具类,你们去掉就行了,或者是使用别的

  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值