电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

java多線程導入excel的方法

瀏覽:138日期:2022-05-22 10:35:05
一、首先是依賴

<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內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: excel
相關文章:
主站蜘蛛池模板: 锌合金压铸-铝合金压铸厂-压铸模具-冷挤压-誉格精密压铸 | 锯边机,自动锯边机,双面涂胶机-建业顺达机械有限公司 | 知网论文检测系统入口_论文查重免费查重_中国知网论文查询_学术不端检测系统 | 智能监控-安防监控-监控系统安装-弱电工程公司_成都万全电子 | 天津货架厂_穿梭车货架_重型仓储货架_阁楼货架定制-天津钢力仓储货架生产厂家_天津钢力智能仓储装备 | 杭州ROHS检测仪-XRF测试仪价格-百科 | 工业雾炮机_超细雾炮_远程抑尘射雾器-世纪润德环保设备 | 无负压供水设备,消防稳压供水设备-淄博创辉供水设备有限公司 | 无尘烘箱_洁净烤箱_真空无氧烤箱_半导体烤箱_电子防潮柜-深圳市怡和兴机电 | 烟台游艇培训,威海游艇培训-烟台市邮轮游艇行业协会 | 江苏密集柜_电动_手动_移动_盛隆柜业江苏档案密集柜厂家 | 干粉砂浆设备-干粉砂浆生产线-干混-石膏-保温砂浆设备生产线-腻子粉设备厂家-国恒机械 | 柔性输送线|柔性链板|齿形链-上海赫勒输送设备有限公司首页[输送机] | 高光谱相机-近红外高光谱相机厂家-高光谱成像仪-SINESPEC 赛斯拜克 | 北京公寓出租网-北京酒店式公寓出租平台 | 连续油炸机,全自动油炸机,花生米油炸机-烟台茂源食品机械制造有限公司 | 氮化镓芯片-碳化硅二极管 - 华燊泰半导体 | 穿线管|波纹穿线管|包塑金属软管|蛇皮管?闵彬专注弱电工程? | 化妆品加工厂-化妆品加工-化妆品代加工-面膜加工-广东欧泉生化科技有限公司 | 活性炭厂家-蜂窝活性炭-粉状/柱状/果壳/椰壳活性炭-大千净化-活性炭 | 锂电混合机-新能源混合机-正极材料混料机-高镍,三元材料混料机-负极,包覆混合机-贝尔专业混合混料搅拌机械系统设备厂家 | 袋式过滤器,自清洗过滤器,保安过滤器,篮式过滤器,气体过滤器,全自动过滤器,反冲洗过滤器,管道过滤器,无锡驰业环保科技有限公司 | 烟气换热器_GGH烟气换热器_空气预热器_高温气气换热器-青岛康景辉 | 厌氧工作站-通用型厌氧工作站-上海胜秋科学仪器有限公司 | 吹田功率计-长创耐压测试仪-深圳市新朗普电子科技有限公司 | 高考志愿规划师_高考规划师_高考培训师_高报师_升学规划师_高考志愿规划师培训认证机构「向阳生涯」 | 真空乳化机-灌装封尾机-首页-温州精灌 | 烟台条码打印机_烟台条码扫描器_烟台碳带_烟台数据采集终端_烟台斑马打印机-金鹏电子-金鹏电子 | 贴板式电磁阀-不锈钢-气动上展式放料阀-上海弗雷西阀门有限公司 工业机械三维动画制作 环保设备原理三维演示动画 自动化装配产线三维动画制作公司-南京燃动数字 | 飞歌臭氧发生器厂家_水处理臭氧发生器_十大臭氧消毒机品牌 | 全温度恒温培养摇床-大容量-立式-远红外二氧化碳培养箱|南荣百科 | 祝融环境-地源热泵多恒系统高新技术企业,舒适生活环境缔造者! | 贴板式电磁阀-不锈钢-气动上展式放料阀-上海弗雷西阀门有限公司 工业机械三维动画制作 环保设备原理三维演示动画 自动化装配产线三维动画制作公司-南京燃动数字 | 安规_综合测试仪,电器安全性能综合测试仪,低压母线槽安规综合测试仪-青岛合众电子有限公司 | 不锈钢反应釜,不锈钢反应釜厂家-价格-威海鑫泰化工机械有限公司 不干胶标签-不干胶贴纸-不干胶标签定制-不干胶标签印刷厂-弗雷曼纸业(苏州)有限公司 | 汽车水泵_汽车水泵厂家-瑞安市骏迪汽车配件有限公司 | 上海诺狮景观规划设计有限公司 | 衡阳耐适防护科技有限公司——威仕盾焊接防护用品官网/焊工手套/焊接防护服/皮革防护手套 | 卓能JOINTLEAN端子连接器厂家-专业提供PCB接线端子|轨道式端子|重载连接器|欧式连接器等电气连接产品和服务 | 电机铸铝配件_汽车压铸铝合金件_发动机压铸件_青岛颖圣赫机械有限公司 | 轴承振动测量仪电箱-轴承测振动仪器-测试仪厂家-杭州居易电气 |