java多线程导入excel的方法

一、首先是依赖

<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi</artifactId>
   <version>3.17</version>
  </dependency>
  <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>

二、导入实现类

package com.supcon.mare.tankinfo.util;

import com.alibaba.excel.util.StringUtils;
import com.supcon.mare.common.util.exception.InterfaceException;
import com.supcon.mare.tankinfo.constant.Constants;
import com.supcon.mare.tankinfo.entity.TankAreaEntity;
import com.supcon.mare.tankinfo.entity.TankMovementEntity;
import com.supcon.mare.tankinfo.repository.TankAreaRepository;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: zhaoxu
 * @description:
 */
public class ExcelThreadUtil implements Runnable {

    Sheet sheet;
    Integer rowIndex;
    List<String> rowNames;
    Integer size = 0;

    TankAreaRepository tankAreaRepository;

    ReflectUtil reflectUtil;

    public volatile static List<TankMovementEntity> tankMovementEntities = new ArrayList<>();

    public void setExcelThreadAttr(Sheet sheet, Integer rowIndex, List<String> rowNames, Integer size, TankAreaRepository tankAreaRepository, ReflectUtil reflectUtil) {
        this.sheet = sheet;
        this.rowIndex = rowIndex;
        this.rowNames = rowNames;
        this.size = size;
        this.tankAreaRepository = tankAreaRepository;
        this.reflectUtil = reflectUtil;
    }

    @Override
    public void run() {
        int index = 0;
        while (sheet.getRow(rowIndex) != null && index < size) {
            TankMovementEntity tankMovementEntity = new TankMovementEntity();
            Integer cellIndex = 0;
            List<String> units = new ArrayList();
            Iterator<Cell> cellIterator = sheet.getRow(rowIndex).cellIterator();
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                cell.setCellType(CellType.STRING);
                String rowName = rowNames.get(cellIndex++);
                try {
                    //解析标题
                    judgeToParse(tankMovementEntity, rowName, cell, units, sheet);
                } catch (Exception e) {
                    throw new InterfaceException(3414, "第" + (cell.getRowIndex() + 1) + "行," + (cell.getColumnIndex() + 1) + "列发生错误:" + cell.toString());
                }
            }
            Boolean hasValue = false;
            try {
                Map<String, Object> fieldsValue = reflectUtil.getFieldsValue(TankMovementEntity.class, tankMovementEntity);
                Iterator<String> fieldKey = fieldsValue.keySet().iterator();
                //如果所有属性为空则不导入
                while (fieldKey.hasNext()) {
                    String key = fieldKey.next();
                    Object value = fieldsValue.get(key);
                    if (!"serialVersionUID".equals(key) && !StringUtils.isEmpty(fieldsValue.get(key))) {
                        hasValue = true;
                        break;
                    }
                }
                tankMovementEntity.setValid(1);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            rowIndex++;
            index++;

            if (!hasValue) {
                continue;
            }
            tankMovementEntity.setGmtCreate(Utils.getNowDate());
            tankMovementEntity.setSupportAddPump(0);
            tankMovementEntity.setSupportDelPump(0);
            tankMovementEntity.setChangeTank(0);
            tankMovementEntity.setSupportUpdatePump(0);
            //解析单元号
            if (units.size() > 1) {
                units.stream().forEach(unit -> {
                    TankAreaEntity tankAreaEntity = tankAreaRepository.findByTankAreaCodeAndValid(unit, Constants.VALID_TRUE);
                    if (tankAreaEntity == null && tankMovementEntity.getTankArea() == null) {
                        tankAreaEntity = new TankAreaEntity();
                        tankAreaEntity.setId(Long.valueOf(1));
                        tankMovementEntity.setTankArea(tankAreaEntity);
                    }
                    List<String> unContainUnit = units.stream().filter(unit1 -> !unit1.equals(unit)).collect(Collectors.toList());
                    StringBuilder goalTankArea = new StringBuilder();
                    unContainUnit.stream().forEach(un -> goalTankArea.append(un + ","));
                    tankMovementEntity.setGoalTankArea(goalTankArea.substring(0, goalTankArea.lastIndexOf(",")));
                    tankMovementEntity.setStrideTankarea(1);
                });
            } else {
                TankAreaEntity tankAreaEntity = null;
                if (units.size() > 0) {
                    tankAreaEntity = tankAreaRepository.findByTankAreaCodeAndValid(units.get(0), Constants.VALID_TRUE);
                }
                if (tankAreaEntity == null && tankMovementEntity.getTankArea() == null) {
                    tankAreaEntity = new TankAreaEntity();

                    tankAreaEntity.setId(Long.valueOf(1));
                }
                tankMovementEntity.setTankArea(tankAreaEntity);
            }
            if (!StringUtils.isEmpty(tankMovementEntity.getGoalTankArea())) {
                tankMovementEntity.setStrideTankarea(1);
            } else {
                tankMovementEntity.setStrideTankarea(0);
            }
            synchronized (tankMovementEntities) {
                tankMovementEntities.add(tankMovementEntity);
            }
        }
    }

    public void judgeToParse(TankMovementEntity tankMovementEntity, String rowName, Cell cell, List<String> units, Sheet sheet) {
        String stringCellValue;

        if (Utils.isMergedRegion(sheet, cell.getRowIndex(), cell.getColumnIndex())) {
            stringCellValue = Utils.getMergedRegionValue(sheet, cell.getRowIndex(), cell.getColumnIndex()).replaceAll("\n", ",");
        } else {
            stringCellValue = cell.getStringCellValue().replaceAll("\n", ",");
        }

        if (StringUtils.isEmpty(stringCellValue)) {
            return;
        }
        //判断是否需要进行转换
        if (Constants.CONTINUITY.equals(stringCellValue)) {
            reflectUtil.setValue(TankMovementEntity.class, tankMovementEntity, rowName, 0);
        } else if (Constants.BATCH.equals(stringCellValue)) {
            reflectUtil.setValue(TankMovementEntity.class, tankMovementEntity, rowName, 1);
        } else if (Constants.YES.equals(stringCellValue)) {
            reflectUtil.setValue(TankMovementEntity.class, tankMovementEntity, rowName, 1);
        } else if (Constants.NO.equals(stringCellValue)) {
            reflectUtil.setValue(TankMovementEntity.class, tankMovementEntity, rowName, 0);
        } else if (Constants.PROVIDE.equals(stringCellValue)) {
            reflectUtil.setValue(TankMovementEntity.class, tankMovementEntity, rowName, 1);
        } else if (Constants.UN_PROVIDE.equals(stringCellValue)) {
            reflectUtil.setValue(TankMovementEntity.class, tankMovementEntity, rowName, 0);
        } else if (Constants.NA.equals(stringCellValue)) {
            reflectUtil.setValue(TankMovementEntity.class, tankMovementEntity, rowName, null);
        } else if (Constants.SOURCE_DEVICE.equals(rowName) || Constants.PUMP_DEVICE.equals(rowName) || Constants.GOAL_DEVICE.equals(rowName) || Constants.VALVE_DEVICE.equals(rowName)) {
            reflectUtil.setValue(TankMovementEntity.class, tankMovementEntity, rowName, stringCellValue);
        } else if ((Constants.TANK_AREA).equals(rowName)) {
            reflectUtil.setValue(TankMovementEntity.class, tankMovementEntity, rowName, tankAreaRepository.findByTankAreaCodeAndValid(stringCellValue, Constants.VALID_TRUE));
        } else if ((Constants.SWITCH_TANK_SOURCE).equals(rowName)) {
            reflectUtil.setValue(TankMovementEntity.class, tankMovementEntity, rowName, "目的".equals(stringCellValue) ? 1 : 0);
        } else if ((Constants.UNIT).equals(rowName)) {
            if (stringCellValue.contains(Constants.COMMA)) {
                String[] split = stringCellValue.split(",");
                units.addAll(Arrays.asList(split));
            } else {
                units.add(stringCellValue);
            }
        } else {
            Class<?> aClass = null;

            try {
                //反射获取字段类型
                String typeName = TankMovementEntity.class.getDeclaredField(rowName).getGenericType().getTypeName();
                aClass = Class.forName(typeName);
            } catch (Exception e) {
                System.out.println(("未找到属性类型:" + rowName));
            }

            if (aClass == Long.class) {
                reflectUtil.setValue(TankMovementEntity.class, tankMovementEntity, rowName, Long.valueOf(stringCellValue));
            } else if (aClass == Integer.class || aClass == int.class) {
                if (Integer.valueOf(stringCellValue) > 1 && !rowName.equals(Constants.MAX_PUMP)) {
                    throw new ClassCastException("解析错误");
                }
                reflectUtil.setValue(TankMovementEntity.class, tankMovementEntity, rowName, Integer.valueOf(stringCellValue));
            } else {
                reflectUtil.setValue(TankMovementEntity.class, tankMovementEntity, rowName, stringCellValue);
            }
        }
    }
}

三、调用多线程

@Override
@Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
public String importFromExcel(String fileString) throws IOException {
    Workbook workbook = null;
    File file = new File("D:\\Google下载\\" + fileString + ".xlsx");
    InputStream is = new FileInputStream(file);
    if (file.getName().endsWith(Constants.XLSX)) {
        workbook = new XSSFWorkbook(is);
    } else if (file.getName().endsWith(Constants.XLS)) {
        workbook = new HSSFWorkbook(is);
    }
    Iterator<Sheet> sheetIterator = workbook.sheetIterator();
    List<String> rowNames = new ArrayList<>();
    while (sheetIterator.hasNext()) {
        Sheet sheet = sheetIterator.next();
        Iterator<Row> rowIterator = sheet.rowIterator();
        Integer rowIndex = 0;
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor((sheet.getLastRowNum() / readNumbers) + 1, (sheet.getLastRowNum() / readNumbers) + 2, 1000, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            //从第二行开始
            if (rowIndex > 0) {
                Iterator<Cell> cellIterator = row.cellIterator();
                //第二行是标题
                if (rowIndex == 1) {
                    //列遍历
                    while (cellIterator.hasNext()) {
                        Cell next = cellIterator.next();
                        next.setCellType(CellType.STRING);
                        String stringCellValue = next.getStringCellValue();
                        rowNames.add(stringCellValue.replaceAll("\n", ""));
                    }
                } else {
                    Cell cell = row.getCell(0);
                    cell.setCellType(CellType.STRING);
                    if (StringUtils.isEmpty(cell.getStringCellValue())) {
                        break;
                    }
                    if ((rowIndex - 2) % readNumbers == 0) {
                        ExcelThreadUtil excelThreadUtil = new ExcelThreadUtil();
                        if ((sheet.getLastRowNum() - rowIndex + 1 < readNumbers * 2 && sheet.getLastRowNum() - rowIndex + 1 > readNumbers)) {
                            Integer size = sheet.getLastRowNum() - rowIndex + 1;
                            excelThreadUtil.setExcelThreadAttr(sheet, rowIndex, rowNames, size, tankAreaRepository, reflectUtil);
                            Future<?> future = threadPoolExecutor.submit(excelThreadUtil);
                            try {
                                future.get();
                            } catch (Exception e) {
                                ExcelThreadUtil.tankMovementEntities.clear();
                                throw new InterfaceException(3414, e.getMessage());
                            }
                            break;
                        }
                        excelThreadUtil.setExcelThreadAttr(sheet, rowIndex, rowNames, readNumbers, tankAreaRepository, reflectUtil);
                        Future<?> future = threadPoolExecutor.submit(excelThreadUtil);
                        try {
                            future.get();
                        } catch (Exception e) {
                            ExcelThreadUtil.tankMovementEntities.clear();
                            throw new InterfaceException(3414, e.getMessage());
                        }
                    }
                }
            }
            rowIndex++;
        }
        threadStop(threadPoolExecutor);
    }
    return "true";
}

判断线程是否都停止:

private void threadStop(ThreadPoolExecutor threadPoolExecutor) {
        while (true) {
            if (threadPoolExecutor.getActiveCount() == 0) {
                ExcelThreadUtil.tankMovementEntities.stream().forEach(tankMovement -> {
                    tankMovement.setTaskDefineCode("move_" + String.valueOf((int) (Math.random() * (1600 - 1 + 1)) + 1) + System.currentTimeMillis());
                    String businessTypeName = tankMovement.getBusinessTypeCode();
                    EnumCodeEntity businessEnumEntity = enumCodeRepository.findByName(businessTypeName);
                    tankMovement.setBusinessTypeCode(businessEnumEntity == null ? businessTypeName : businessEnumEntity.getTypeCode());
                    Integer random = (int) (Math.random() * (2 - 1 + 1)) + 1;
                    tankMovement.setMaterialTypeCode(String.valueOf(random));
                    TankAreaEntity tankAreaEntity = new TankAreaEntity();
                    tankAreaEntity.setId(Long.valueOf((int) (Math.random() * (16 - 1 + 1)) + 1));
                    tankMovement.setTankArea(tankAreaEntity);
                });
                tankMovementRepository.saveAll(ExcelThreadUtil.tankMovementEntities);
                ExcelThreadUtil.tankMovementEntities.clear();
                break;
            }
        }
    }

到此这篇关于java多线程导入excel的方法的文章就介绍到这了,更多相关java多线程导入excel内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Java利用POI实现导入导出Excel表格示例代码

    介绍 Jakarta POI 是一套用于访问微软格式文档的Java API.Jakarta POI有很多组件组成,其中有用于操作Excel格式文件的HSSF和用于操作Word的HWPF,在各种组件中目前只有用于操作Excel的HSSF相对成熟.官方主页http://poi.apache.org/index.html,API文档http://poi.apache.org/apidocs/index.html 实现 已经在代码中加入了完整的注释. import java.io.FileInputSt

  • Java实现批量导入excel表格数据到数据库中的方法

    本文实例讲述了Java实现批量导入excel表格数据到数据库中的方法.分享给大家供大家参考,具体如下: 1.创建导入抽象类 package com.gcloud.common.excel; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.sql.SQLException;

  • Java数据导入功能之读取Excel文件实例

    在编程中经常需要使用到表格(报表)的处理主要以Excel表格为主.下面给出用java读取excel表格方法: 1.添加jar文件 java导入导出Excel文件要引入jxl.jar包,最关键的是这套API是纯Java的,并不依赖Windows系统,即使运行在Linux下,它同样能够正确的处理Excel文件.下载地址:http://www.andykhan.com/jexcelapi/ 2.jxl对Excel表格的认识 (1)每个单元格的位置认为是由一个二维坐标(i,j)给定,其中i表示列,j表示

  • Java POI实现将导入Excel文件的示例代码

    问题描述 现需要批量导入数据,数据以Excel形式导入. POI介绍 我选择使用的是apache POI.这是有Apache软件基金会开放的函数库,他会提供API给java,使其可以对office文件进行读写. 我这里只需要使用其中的Excel部分. 实现 首先,Excel有两种格式,一种是.xls(03版),另一种是.xlsx(07版).针对两种不同的表格格式,POI对应提供了两种接口.HSSFWorkbook和XSSFWorkbook 导入依赖 <dependency> <group

  • Java将excel中的数据导入到mysql中

    我们在实际工作中的一些时候会需要将excel中的数据导入数据库,如果你的数据量成百上千甚至更多,相信一点点ctrlc.ctrlv也不是办法,这里我们以mysql数据库为例,将excel中的数据存入数据库. 我的思路是:先将excel中的数据取出来,再把数据传入数据库,操作excel需要jxl.jar,操作数据库可以用最基本的jdbc,需要mysql-connector-java-5.0.8-bin.jar这个jar包. 下面我们先看一下excel截图: 再来看最后的效果图: 下面贴出整个代码:

  • java的poi技术读取和导入Excel实例

    报表输出是Java应用开发中经常涉及的内容,而一般的报表往往缺乏通用性,不方便用户进行个性化编辑.Java程序由于其跨平台特性,不能直接操纵Excel.因此,本文探讨一下POI视线Java程序进行Excel的读取和导入. 项目结构: java_poi_excel 用到的Excel文件: xls XlsMain .java 类 //该类有main方法,主要负责运行程序,同时该类中也包含了用poi读取Excel(2003版) import java.io.FileInputStream; impor

  • Java如何将Excel数据导入到数据库

    本文实例为大家分享了Java将Excel数据导入到数据库的具体代码,供大家参考,具体内容如下 所用Jar包 1. sqljdbc4.jar 连接数据库的Jar包(根据数据库的不同进行选择,我用的SqlServer2008) 2.Jxl.jar 访问Excel的Jar包 package xsl; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; impo

  • java实现Excel的导入导出

    本文实例为大家分享了java实现Excel导入导出的具体代码,供大家参考,具体内容如下 一.Excel读写技术 区别: 二.jxl读写基础代码 1.从数据库将数据导出到excel表格 public class JxlExcel { public static void main(String[] args) { //创建Excel文件 String[] title= {"姓名","课程名","分数"}; File file=new File(&q

  • java使用POI批量导入excel数据的方法

    一.定义 Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能. 二.所需jar包: 三.简单的一个读取excel的demo 1.读取文件方法 /** * 读取出filePath中的所有数据信息 * @param filePath excel文件的绝对路径 * */ public static void getDataFromExcel(String filePath) { //String fileP

  • 在java poi导入Excel通用工具类示例详解

    前言 本文主要给大家介绍了关于java poi导入Excel通用工具类的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧. 问题引入和分析 提示:如果不想看罗嗦的文章,可以直接到最后点击源码下载运行即可 最近在做一个导入Excel的功能,在做之前在百度上面查找"java通用导入Excel工具类",没有查到,大多数都是java通用导出Excel.后来仔细想想,导出可以利用java的反射,做成通用的,放进相应的实体成员变量中,导入为什么不可以呢?也是可以的,不过在做

随机推荐