POI批量添加Demo

Posted xanlv

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    

以上是关于POI批量添加Demo的主要内容,如果未能解决你的问题,请参考以下文章

java实现文件批量导入导出实例(兼容xls,xlsx)

Spark[四]——Spark并行度

Java实现文件批量导入导出实例(兼容xls,xlsx)

POI 导出大批量数据的Excel

使用poi进行数据的导出Demo

JAVA使用poi包,向Excel中写入批量数据