POI批量添加Demo

maven工程

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

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

            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
                <version>3.17</version>
            </dependency>
            <dependency>
                <groupId>org.apache.xmlbeans</groupId>
                <artifactId>xmlbeans</artifactId>
                <version>2.5.0</version>
            </dependency>
package controller;

import bean.UserExcelVO;
import common.CommonResponse;
import service.IUserService;
import util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 批量添加用户
     */
    @RequestMapping(value = "/batch", method = RequestMethod.POST)
    @ResponseBody
    public CommonResponse addByBatch(HttpServletRequest request, HttpServletResponse response) {

        List<UserExcelVO> userExcelVOList = ExcelUtil.readUserExcel(request);
        if (userExcelVOList == null) {//配置事件
            return new CommonResponse(false, "文件格式错误...");
        }
        int i;
        try {
            i = userService.insertAllUser(userExcelVOList);
        } catch (Exception e) {
            return new CommonResponse(false, "插入失败.请检查员工帐号是否重复....");
        }
        return new CommonResponse(true, i);
    }
}
package util;

import com.google.common.collect.Lists;
import bean.UserExcelVO;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * created by zhimin.xu on 2018/3/5
 * discription:解析 excel文件
 */
public class ExcelUtil {
    private static final Logger logger = LoggerFactory.getLogger(ExcelUtil.class);

    public static List<UserExcelVO> readUserExcel(HttpServletRequest request) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        //获得文件:
        MultipartFile contactFile = multiRequest.getFile("file");
        //解析excel失败原因一:"file"不对,,需要看下前端是否给excel文件设置了名字,需要改为相应的文件名
        logger.info("excel excelFile: -->{}", contactFile);
        if (contactFile == null || contactFile.isEmpty()) {
            return null;
        }
        Workbook workbook = null;
        try {
            workbook = WorkbookFactory.create(contactFile.getInputStream());
            logger.info("excel workbook: -->{}", workbook);
        } catch (IOException e) {
            logger.error("create excel IOException: -->{}", e);
            return null;
        } catch (InvalidFormatException e) {
            logger.error("create excel InvalidFormatException: -->{}", e);
            return null;
        }
        List<UserExcelVO> userExcelVOList = Lists.newArrayList();
        UserExcelVO userExcelVO;
        for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
            Sheet sheet = workbook.getSheetAt(numSheet);
            if (sheet == null) {
                continue;
            }
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);
                if (row == null) {
                    continue;
                }
                userExcelVO = new UserExcelVO();
                userExcelVO.setAdName(String.valueOf(row.getCell(1)));//AD姓名 0开始
                userExcelVO.setAdAccount(String.valueOf(row.getCell(2)));//AD账号
                userExcelVO.setPhone(String.valueOf(row.getCell(7)));//移动电话 13
                userExcelVO.setEducationLevel(String.valueOf(row.getCell(8)));最高教育程度14
                userExcelVO.setInductionDate(String.valueOf(row.getCell(9)));//入职日期 23
                userExcelVO.setWorkArea(String.valueOf(row.getCell(10)));//工作地区 24
                userExcelVO.setPositionLevel(String.valueOf(row.getCell(18)));//职级40
                userExcelVO.setGender(String.valueOf(row.getCell(19)));//性别41
                userExcelVO.setPosition(String.valueOf(row.getCell(20)));//职务42
                logger.info("userExcelVO: --> {}", userExcelVO);
                userExcelVOList.add(userExcelVO);
            }
        }
        return userExcelVOList;
    }
}
//出现了异常就会发生回滚
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
    @Override
    public int insertAllUser(List<UserExcelVO> userExcelVOList) {
        for (UserExcelVO userExcelVO : userExcelVOList) {
            UserDO userDO = VOToDOUtil.transformUserExcelVO(userExcelVO);

            userDao.insertUserSelective(userDO);
        }
        return 0;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值