美文网首页
导入excel

导入excel

作者: ShrJanLan | 来源:发表于2020-05-10 20:08 被阅读0次

1.文件上传(这里使用了layui前端框架,上传接口返回参数必须为json)

    layui.use(['layer', 'upload'], function(){
        var upload = layui.upload;
        var layer = layui.layer;
        //执行实例
        //导入店铺
        upload.render({
            elem: '#importStores' //绑定元素
            ,url: '${pageContext.request.contextPath}/stores/bulkImport' //上传接口
            ,done: function(res){
                //上传完毕回调
                layer.msg(res.msg);
            }
            ,accept: 'file'
            //上传文件需为xls或xlsx
            ,acceptMime: 'application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            ,error: function(){
                //请求异常回调
                layer.msg("导入失败!");
            }
        });
    });

2.StatusCode

/**
 * 统一的状态码定义
 */
public enum StatusCode {

    Success(0,"成功"),
    Fail(-1,"失败"),
    InvalidParams(201,"非法的参数!"),

    ImportSuccess(1001,"导入成功"),
    ImportFail(-1001,"导入失败");

//    UserNamePasswordNotBlank(50000,"账户密码不能为空!"),
//    AccessTokenNotBlank(50001,"accessToken必填,请在请求头header中塞入该字段"),
//
//    TokenValidateExpireToken(60001,"Token已过期"),
//    TokenValidateCheckFail(60002,"Token验证失败"),
//
//    AccessTokenNotExist(70001,"Token不存在-请重新登录!"),
//    AccessTokenInvalidate(70002,"无效的Token!"),
//
//    AccessTokenNotExistRedis(80001,"Token不存在或已经过期-请重新登录!"),
//
//    AccessSessionNotExist(90001,"用户没登录或登录Session已经过期-请重新登录!"),
//
//    LoginFail(100000,"登录失败!"),
//    CurrUserHasNotPermission(100001,"当前用户没有权限访问该资源或者操作!"),
//    CurrUserNotLogin(100002,"当前用户没有登录,请先进行登录!");

    private Integer code;
    private String msg;

    StatusCode(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

3.BaseResponse

import com.lst.api.enums.StatusCode;

/**
 * 统一的响应数据模型
 */
public class BaseResponse<T> {

    private Integer code;
    private String msg;
    private T data;

    public BaseResponse(StatusCode statusCode, T data) {
        this.code = statusCode.getCode();
        this.msg = statusCode.getMsg();
        this.data = data;
    }

    public BaseResponse(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public BaseResponse(StatusCode statusCode) {
        this.code = statusCode.getCode();
        this.msg = statusCode.getMsg();
    }

    public BaseResponse(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

4.工具类

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.*;

/**
 * 读取excel信息工具类
 */
public class ReadExcelUtil {

    //总行数
    private int totalRows = 0;
    //总条数
    private int totalCells = 0;

    public int getTotalRows() {
        return totalRows;
    }

    public int getTotalCells() {
        return totalCells;
    }

    /**
     * 读取excel信息
     * @param file
     * @return
     */
    public Sheet readExcel(MultipartFile file) throws Exception{
        // 1)HSSFWorkbook,针对office 97-2003,也就是以.xls扩展名结尾的excel文件
        // 2)XSSFWorkbook,针对offic2007及以上的,也就是以.xlsx扩展名结尾的excel文件
        //判断文件是否为空
        if(file==null) return null;
        //获取文件名
        String name=file.getOriginalFilename();
        //进一步判断文件是否为空(即判断其大小是否为0或其名称是否为null)
        long size=file.getSize();
        if(name==null || ("").equals(name) && size==0) return null;
        //获取文件后缀名
        String suffix = name.substring(name.lastIndexOf(".")+1);
        Sheet sheet = null;
        try {
            if("xls".equals(suffix)){
                sheet = readHw(file);
            }else if("xlsx".equals(suffix)){
                sheet = readXw(file);
            }else{
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sheet;
    }

    /**
     * office 97-2003
     * @param file
     * @return
     * @throws Exception
     */
    private Sheet readHw(MultipartFile file) throws Exception{
        HSSFWorkbook hw = null;
        HSSFSheet sheet = null;
        try {
            hw = new HSSFWorkbook(file.getInputStream());
            //得到第一个shell
            sheet = hw.getSheetAt(0);

            //得到Excel的行数
            this.totalRows = sheet.getPhysicalNumberOfRows();

            //得到Excel的列数(前提是有行数)
            if(this.totalRows>=1 && sheet.getRow(0) != null){
                this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            try {
                hw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sheet;
    }

    /**
     * offic2007及以上
     * @param file
     * @return
     * @throws Exception
     */
    private Sheet readXw(MultipartFile file) throws Exception{
        XSSFWorkbook xw = null;
        XSSFSheet sheet = null;
        try {
            xw = new XSSFWorkbook(file.getInputStream());
            //得到第一个shell
            sheet = xw.getSheetAt(0);

            //得到Excel的行数
            this.totalRows = sheet.getPhysicalNumberOfRows();

            //得到Excel的列数(前提是有行数)
            if(this.totalRows>=1 && sheet.getRow(0) != null){
                this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            try {
                xw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sheet;
    }

}

5.遍历excel

    @Transactional
    @Override
    public void bulkImport(MultipartFile file) throws Exception {
        ReadExcelUtil reu = new ReadExcelUtil();
        Sheet sheet = reu.readExcel(file);
        if(sheet==null){
            throw new RuntimeException("读取工作表失败!");
        }
        //当前时间
        Date current = DateUtil.getCurrentDate();
        List<String> column = new ArrayList<>();//存储列名
        List<Stores> list = new ArrayList<>();
        for (int r = 0;r<reu.getTotalRows();r++) {
            Row row = sheet.getRow(r);
            if (row == null) continue;
            //循环Excel的列
            Stores stores = new Stores();
            for(int c = 0; c <reu.getTotalCells(); c++){
                Cell cell = row.getCell(c);
                cell.setCellType(Cell.CELL_TYPE_STRING);//设置Cell的类型
                String value = cell.getStringCellValue();
                //去除回车或换行
                value = value.replaceAll("\r|\n", "");
                if(r==0){//获取列名
                    column.add(value);
                }else{
                    if("店铺名称".equals(column.get(c))){
                        stores.setName(value);
                    }
                }
            }
            if(r!=0){
                stores.setCreateTime(current);
                stores.setUpdateTime(current);
                stores.setIsDelete(false);//默认有效
                list.add(stores);
            }
        }
        if(list.size()>99){//SqlServer 对语句的条数和参数的数量都有限制,分别是 1000 和 2100。
            List<Stores> lists = new ArrayList<>();
            for (int i=0;i<list.size();i++){
                lists.add(list.get(i));
                if(i!=0 && i%99==0 || i==list.size()-1){//每100条批量导入
                    //批量导入
                    storesMapper.bulkImport(lists);
                    lists = new ArrayList<>();
                }
            }
        }else{
            //批量导入
            storesMapper.bulkImport(list);
        }
    }

批量导入

相关文章

网友评论

      本文标题:导入excel

      本文链接:https://www.haomeiwen.com/subject/alksnhtx.html