package com.sercurityControl.proteam.util; import com.alibaba.fastjson2.JSONObject; import com.securityControl.common.core.exception.ServiceException; import com.securityControl.common.core.utils.DateUtils; import com.securityControl.common.core.utils.aes.StringHelper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ooxml.POIXMLDocumentPart; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.*; import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.CollectionUtils; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ImportExcelUtils { private static final Logger log = LoggerFactory.getLogger(ImportExcelUtils.class); private static final List proNameList = new LinkedList<>(); public static List readExcel(MultipartFile file, Class mClass, String uploadPath) throws Exception { String fileName = file.getOriginalFilename(); log.info("OriginalFilename:{}", fileName); if (!StringUtils.endsWithAny(fileName, ".xls", ".xlsx")) { throw new ServiceException("不支持excel以外的文件导入!"); } List list = new ArrayList<>(); InputStream inputStream = file.getInputStream(); String className = mClass.getSimpleName(); log.info("className:{}", className); //根据指定的文件输入流导入Excel从而产生Workbook对象 Workbook workbook = null; Sheet sheet = null; Map mapData = null; if (null != fileName && fileName.endsWith(".xls")) { workbook = new HSSFWorkbook(inputStream); //获取Excel文档中的第一个表单 sheet = workbook.getSheetAt(0); if (!checkModal(sheet, className)) { throw new ServiceException("模板错误,请重新选择模板!"); } mapData = getPicturesXls((HSSFSheet) sheet, className); } if (null != fileName && fileName.endsWith(".xlsx")) { workbook = new XSSFWorkbook(inputStream); //获取Excel文档中的第一个表单 sheet = workbook.getSheetAt(0); if (!checkModal(sheet, className)) { throw new ServiceException("模板错误,请重新选择模板!"); } mapData = getPicturesXlsx((XSSFSheet) sheet, className); } List> filenames = new ArrayList<>(); if ("TRiskPressDropRate".equals(className)) { log.info("开始读取并写入图片"); filenames = writeImg(mapData, className, uploadPath); log.info("图片:{},写入完成!", filenames); } int sheetCount = 0; if (workbook != null) { workbook.getNumberOfSheets(); } log.info("Sheet(表单)数量:{}", sheetCount); log.info("filenames:{}", filenames); //获得最后一条记录得的行号,从0开始 int totalRowNum = 0; if (sheet != null) { totalRowNum = sheet.getLastRowNum(); } log.info("总记录数:{}", (totalRowNum + 1)); list = createBean(sheet, mClass, filenames); inputStream.close(); return list; } private static boolean checkModal(Sheet sheet, String className) { int colNum = sheet.getRow(0).getLastCellNum(); if ("TRiskPressDropRate".equals(className)) { return colNum == 32; } else if ("DeviceController".equals(className)) { return colNum == 13; } else if ("TyDeviceController".equals(className)) { return colNum == 21; } else if ("PreservationController".equals(className)) { return colNum == 21; } return false; } private static List createBean(Sheet sheet, Class mClass, List> filename) throws Exception { if (sheet == null || sheet.getLastRowNum() < 0) { return null; } List list = new ArrayList<>(); int last = sheet.getRow(0).getLastCellNum();// 总列数 log.info("列数:{}", last); try { for (Row row : sheet) { if (row == null) { continue; } // 第一行是标题栏 if ("TRiskPressDropRate".equals(mClass.getSimpleName())) { if (row.getRowNum() < 2) { continue; } } else if ("TyDeviceController".equals(mClass.getSimpleName())) { if (row.getRowNum() < 3) { continue; } } else { if (row.getRowNum() < 1) { continue; } } boolean isBlankRow = true; for (Cell c : row) { if (c.getCellType() != CellType.BLANK) { isBlankRow = false; break; } } if (isBlankRow) { continue; } JSONObject obj = new JSONObject(); obj.put("rowNo", row.getRowNum() + 1); if ("TRiskPressDropRate".equals(mClass.getSimpleName())) { setExcleTString(32, row); if (row.getCell(1) != null){ // 工程名称 obj.put("proName", row.getCell(1).getStringCellValue()); } if (row.getCell(2) != null){ // 塔号 obj.put("tower", row.getCell(2).getStringCellValue()); } if (row.getCell(3) != null){ // 经度 obj.put("lon", row.getCell(3).getStringCellValue()); } if (row.getCell(4) != null){ // 纬度 obj.put("lat", row.getCell(4).getStringCellValue()); } if (row.getCell(5) != null){ // 基础施工风险-基础类型 obj.put("basicBaseType", row.getCell(5).getStringCellValue()); } if (row.getCell(6) != null){ // 基础施工风险-作业方式 obj.put("basicWorkStyle", row.getCell(6).getStringCellValue()); } if (row.getCell(7) != null){ // 基础施工风险-风险等级 obj.put("basicRiskLevel", row.getCell(7).getStringCellValue()); } if (row.getCell(8) != null){ // 基础施工风险-3级及以上风险作业工序 obj.put("basicOperProcedure", row.getCell(8).getStringCellValue()); } if (row.getCell(9) != null){ // 基础施工风险-工法应用 obj.put("basicAppMethod", row.getCell(9).getStringCellValue()); } if (row.getCell(10) != null){ // 组塔施工风险-杆塔全高 obj.put("groupTowerFullHeight", row.getCell(10).getStringCellValue()); } if (row.getCell(11) != null){ // 组塔施工风险-组塔方式 obj.put("groupTowerStyle", row.getCell(11).getStringCellValue()); } if (row.getCell(12) != null){ // 组塔施工风险-风险等级 obj.put("groupTowerRiskLevel", row.getCell(12).getStringCellValue()); } if (row.getCell(13) != null){ // 组塔施工风险-3级及以上风险作业工序 obj.put("groupTowerOperProcedure", row.getCell(13).getStringCellValue()); } if (row.getCell(14) != null){ // 组塔施工风险-工法应用 obj.put("groupTowerAppMethod", row.getCell(14).getStringCellValue()); } if (row.getCell(15) != null){ // 架线施工风险-跨越物(面向大号) obj.put("wireSpan", row.getCell(15).getStringCellValue()); } if (row.getCell(16) != null){ // 架线施工风险-放线方式 obj.put("wireStyle", row.getCell(16).getStringCellValue()); } if (row.getCell(17) != null){ // 架线施工风险-风险等级 obj.put("wireRiskLevel", row.getCell(17).getStringCellValue()); } if (row.getCell(18) != null){ // 架线施工风险-3级及以上风险作业工序 obj.put("wireOperProcedure", row.getCell(18).getStringCellValue()); } if (row.getCell(19) != null){ // 架线施工风险-工法应用 obj.put("wireAppMethod", row.getCell(19).getStringCellValue()); } // 塔位及周边环境-杆位原始地貌图片 String result1 = "GAYS" + "_" + row.getRowNum(); for (Map map : filename) { for (String key_name : map.keySet()) { if (Objects.equals(result1, key_name)) { obj.put("landFormPath", map.get(key_name)); } } } //塔位及周边环境-A1-A2档内实景图片 String result2 = "DANS" + "_" + row.getRowNum(); for (Map map : filename) { for (String key_name : map.keySet()) { if (Objects.equals(result2, key_name)) { obj.put("surroundingsPath", map.get(key_name)); } } } if (row.getCell(22) != null){ // “8+2”类风险1风险类型 obj.put("riskType", row.getCell(22).getStringCellValue()); } if (row.getCell(23) != null){ // “8+2”类风险1风险明细 obj.put("riskDetails", row.getCell(23).getStringCellValue()); } if (row.getCell(24) != null){ // “8+2”类风险2风险类型 obj.put("riskType2", row.getCell(24).getStringCellValue()); } if (row.getCell(25) != null){ // “8+2”类风险2风险明细 obj.put("riskDetails2", row.getCell(25).getStringCellValue()); } if (row.getCell(26) != null){ // “8+2”类风险3风险类型 obj.put("riskType3", row.getCell(26).getStringCellValue()); } if (row.getCell(27) != null){ // “8+2”类风险3风险明细 obj.put("riskDetails3", row.getCell(27).getStringCellValue()); } if (row.getCell(28) != null){ // “8+2”类风险4风险类型 obj.put("riskType4", row.getCell(28).getStringCellValue()); } if (row.getCell(29) != null){ // “8+2”类风险4风险明细 obj.put("riskDetails4", row.getCell(29).getStringCellValue()); } if (row.getCell(30) != null){ // “8+2”类风险4风险类型 obj.put("riskType5", row.getCell(30).getStringCellValue()); } if (row.getCell(31) != null){ // “8+2”类风险4风险明细 obj.put("riskDetails5", row.getCell(31).getStringCellValue()); } } else if ("DeviceController".equals(mClass.getSimpleName())) { setExcleTString(13, row); if (row.getCell(1) != null) { // 设备名称 obj.put("deviceName", row.getCell(1).getStringCellValue().trim()); } if (row.getCell(2) != null) { // 国网编码 obj.put("macId", row.getCell(2).getStringCellValue().trim()); } if (row.getCell(3) != null) { // 国网编码 obj.put("gbCode", row.getCell(3).getStringCellValue().trim()); } if (row.getCell(4) != null) { // puId obj.put("puId", row.getCell(4).getStringCellValue().trim()); } if (row.getCell(5) != null) { // 所属单位 obj.put("ssdw", row.getCell(5).getStringCellValue().trim()); } if (row.getCell(6) != null) { // 设备类型 obj.put("deviceType", row.getCell(6).getStringCellValue().trim()); } if (row.getCell(7) != null) { // 是否接入统一视频平台 obj.put("isT", row.getCell(7).getStringCellValue().trim()); } if (row.getCell(8) != null) { // 统一视频名称 obj.put("tName", row.getCell(8).getStringCellValue().trim()); } if (row.getCell(9) != null) { // 统一18位编码 obj.put("tCode", row.getCell(9).getStringCellValue().trim()); } if (row.getCell(10) != null) { // 统一前端协议编码 obj.put("twCode", row.getCell(10).getStringCellValue().trim()); } if (row.getCell(11) != null) { // 统一设备协议编码 obj.put("tdCode", row.getCell(11).getStringCellValue().trim()); } if (row.getCell(12) != null) { // 备注 obj.put("remarks", row.getCell(12).getStringCellValue().trim());//备注 } } else if ("TyDeviceController".equals(mClass.getSimpleName())) { setExcleTString(32, row); if (row.getCell(1) != null) { //省公司 String str = row.getCell(1).getStringCellValue(); if (StringHelper.isNotEmpty(str)) { String[] strs = str.split("\\."); int length = strs.length - 1; obj.put("org", strs[length].trim()); } } if (row.getCell(2) != null) { //变电工程名称 obj.put("proName", row.getCell(2).getStringCellValue().trim()); } if (row.getCell(3) != null) { //单项工程名称 obj.put("signName", row.getCell(3).getStringCellValue().trim()); } if (row.getCell(4) != null) { //输变电工程电压等级 obj.put("voltage", row.getCell(4).getStringCellValue().trim()); } if (row.getCell(5) != null) { //工程类型 obj.put("proType", row.getCell(5).getStringCellValue().trim()); } if (row.getCell(6) != null) { //设计单位 obj.put("sjUnit", row.getCell(6).getStringCellValue().trim()); } if (row.getCell(7) != null) { //评审单位 obj.put("psUnit", row.getCell(7).getStringCellValue().trim()); } if (row.getCell(8) != null) { //评审意见印发时间 String str = row.getCell(8).getStringCellValue().trim(); Date time = HSSFDateUtil.getJavaDate(Double.parseDouble(str)); String times = DateTimeHelper.format(time, "yyyy-MM-dd"); obj.put("psYjTime", times); } if (row.getCell(9) != null) { //是否发生设计质量问题 obj.put("isSjzlQ", row.getCell(9).getStringCellValue().trim()); } if (row.getCell(10) != null) { //是否问题库内问题(是/否) obj.put("isQ", row.getCell(10).getStringCellValue().trim()); } if (row.getCell(11) != null) { //设计质量问题名称 obj.put("sjzlQName", row.getCell(11).getStringCellValue().trim()); } if (row.getCell(12) != null) { //问题库编号 obj.put("wtkNum", row.getCell(12).getStringCellValue().trim()); } if (row.getCell(13) != null) { //问题类别 obj.put("wtType", row.getCell(13).getStringCellValue().trim()); } if (row.getCell(14) != null) { //问题性质 obj.put("wtXz", row.getCell(14).getStringCellValue().trim()); } if (row.getCell(15) != null) { //设计阶段 obj.put("sjjd", row.getCell(15).getStringCellValue().trim()); } if (row.getCell(16) != null) { //所属专业 obj.put("sszy", row.getCell(16).getStringCellValue().trim()); } if (row.getCell(17) != null) { //是否整改 obj.put("sfzg", row.getCell(17).getStringCellValue().trim()); } if (row.getCell(18) != null) { //问题简述 obj.put("wtjs", row.getCell(18).getStringCellValue().trim()); } if (row.getCell(19) != null) { //问题分析 obj.put("wtfx", row.getCell(19).getStringCellValue().trim()); } if (row.getCell(20) != null) { //建议采取措施 obj.put("jycqcs", row.getCell(20).getStringCellValue().trim()); } } else if ("PreservationController".equals(mClass.getSimpleName())) { setExcleTString(21, row); if (row.getCell(1) != null) { obj.put("unit", row.getCell(1).getStringCellValue().trim()); } if (row.getCell(2) != null) { obj.put("aq_code", row.getCell(2).getStringCellValue().trim()); } if (row.getCell(3) != null) { obj.put("pro_name", row.getCell(3).getStringCellValue().trim()); } if (row.getCell(4) != null) { obj.put("zsgcfw", row.getCell(4).getStringCellValue().trim()); } if (row.getCell(5) != null) { obj.put("gcgm", row.getCell(5).getStringCellValue().trim()); } if (row.getCell(6) != null) { obj.put("aqzj", row.getCell(6).getStringCellValue().trim()); } if (row.getCell(7) != null) { obj.put("org", row.getCell(7).getStringCellValue().trim()); } if (row.getCell(8) != null) { obj.put("jldw", row.getCell(8).getStringCellValue().trim()); } if (row.getCell(9) != null) { obj.put("sgdw", row.getCell(9).getStringCellValue().trim()); } if (row.getCell(10) != null) { obj.put("gcwz", row.getCell(10).getStringCellValue().trim()); } if (row.getCell(11) != null) {// 时间 String str = row.getCell(11).getStringCellValue().trim(); if (StringUtils.isNumeric(str)) { Date time = HSSFDateUtil.getJavaDate(Double.parseDouble(str)); String times = DateTimeHelper.format(time, "yyyy/MM/dd"); obj.put("jhkgsj", times); } else { obj.put("jhkgsj", str); } } if (row.getCell(12) != null) { String str = row.getCell(12).getStringCellValue().trim(); if (StringUtils.isNumeric(str)) { Date time = HSSFDateUtil.getJavaDate(Double.parseDouble(str)); String times = DateTimeHelper.format(time, "yyyy/MM/dd"); obj.put("jhjgsj", times); } else { obj.put("jhjgsj", str); } } if (row.getCell(13) != null) { obj.put("gcjd", row.getCell(13).getStringCellValue().trim()); } if (row.getCell(14) != null) { obj.put("gczt", row.getCell(14).getStringCellValue().trim()); } if (row.getCell(15) != null) { obj.put("risklevel", row.getCell(15).getStringCellValue().trim()); } if (row.getCell(16) != null) { obj.put("risk_ly", row.getCell(16).getStringCellValue().trim()); } if (row.getCell(17) != null) { String str = row.getCell(17).getStringCellValue().trim(); if (StringUtils.isNumeric(str)) { Date time = HSSFDateUtil.getJavaDate(Double.parseDouble(str)); String times = DateTimeHelper.format(time, "yyyy/MM/dd"); obj.put("update_time", times); } else { obj.put("update_time", str); } } if (row.getCell(18) != null) { String str = row.getCell(18).getStringCellValue().trim(); if (StringUtils.isNumeric(str)) { Date time = HSSFDateUtil.getJavaDate(Double.parseDouble(str)); String times = DateTimeHelper.format(time, "yyyy/MM/dd"); obj.put("next_time", times); } else { obj.put("next_time", str); } } if (row.getCell(19) != null) { obj.put("next_import", row.getCell(19).getStringCellValue().trim()); } if (row.getCell(20) != null) { obj.put("remarks", row.getCell(20).getStringCellValue().trim()); } } list.add(obj); } } catch (IllegalStateException e) { e.printStackTrace(); throw new ServiceException("模板中含有单元格数据格式不正确"); } return list; } /** * 获取图片和位置 (xlsx) * * @param sheet * @return * @throws IOException */ public static Map getPicturesXlsx(XSSFSheet sheet, String className) throws IOException { Map map = new HashMap<>(16); List list = sheet.getRelations(); for (POIXMLDocumentPart part : list) { if (part instanceof XSSFDrawing) { XSSFDrawing drawing = (XSSFDrawing) part; List shapes = drawing.getShapes(); for (XSSFShape shape : shapes) { XSSFPicture picture = (XSSFPicture) shape; XSSFClientAnchor anchor = picture.getPreferredSize(); CTMarker marker = anchor.getFrom(); Row row = sheet.getRow(marker.getRow()); if (row == null) { continue; } String key_name = null; if ("TRiskPressDropRate".equals(className)) { key_name = setKey(picture, row, "TRiskPressDropRate"); } else { key_name = ""; } map.put(key_name, picture.getPictureData()); } } } return map; } /** * 获取图片和位置 (xls) * * @param sheet * @return * @throws IOException */ public static Map getPicturesXls(HSSFSheet sheet, String className) throws IOException { int i = 0; Map map = new HashMap(16); if (sheet.getDrawingPatriarch() != null) { List list = sheet.getDrawingPatriarch().getChildren(); for (HSSFShape shape : list) { if (shape instanceof HSSFPicture) { HSSFPicture picture = (HSSFPicture) shape; int pictureIndex = ((HSSFPicture) shape).getPictureIndex(); if (pictureIndex != -1) { HSSFClientAnchor cAnchor = picture.getClientAnchor(); Row row = sheet.getRow(cAnchor.getRow1()); if (row == null) { continue; } String key_name = null; if (cAnchor.getCol1() == 20) { proNameList.add(row.getCell(1).getStringCellValue()); key_name = "GAYS" + "_" + cAnchor.getRow1(); } else if (cAnchor.getCol1() == 21) { proNameList.add(row.getCell(1).getStringCellValue()); key_name = "DANS" + "_" + cAnchor.getRow1(); } map.put(key_name, picture.getPictureData()); } } } } return map; } //图片写出 public static List> writeImg(Map mapData, String className, String uploadPath) throws IOException { if (mapData == null || mapData.size() == 0) { return new ArrayList<>(); } Object keyArr[] = mapData.keySet().toArray(); ArrayList> filename = new ArrayList<>(); for (int i = 0; i < mapData.size(); i++) { Map map = new HashMap<>(16); // 获取图片流 PictureData pic = mapData.get(keyArr[i]); // 获取图片索引 String picName = keyArr[i].toString(); byte[] data = pic.getData(); String picPath = null; if ("TRiskPressDropRate".equals(className)) { picPath = uploadPath + File.separator + "riskBlood" + File.separator; } // 图片保存路径 if (!CollectionUtils.isEmpty(proNameList)) { File file = new File(picPath + DateUtils.getDate().replace("-", "/") + "/" + proNameList.get(i)); if (!file.exists()) { if (file.mkdirs()) { log.info("-----文件创建成功------"); } else { log.error("======导入图片文件生成失败====="); } } UUID uuid = UUID.randomUUID(); FileOutputStream out = new FileOutputStream(picPath + DateUtils.getDate().replace("-", "/") + "/" + proNameList.get(i) + "/" + picName + uuid + ".jpg"); out.write(data); out.flush(); out.close(); map.put(picName + "", "/riskBlood/" + DateUtils.getDate().replace("-", "/") + "/" + proNameList.get(i) + "/" + picName + uuid + ".jpg"); filename.add(map); } } return filename; } private static String setKey(XSSFPicture picture, Row row, String className) { if (row == null) { return null; }; String result = picture.getPreferredSize().toString(); String pattern = "\\[1-9]\\d*\\<\\/xdr\\:col\\>"; Pattern r = Pattern.compile(pattern); String col = ""; Matcher m = r.matcher(result); if (m.find()) { col = m.group(0); } else { System.out.println("NO MATCH"); } if ("TRiskPressDropRate".equals(className)) { switch (col) { case "20": proNameList.add(row.getCell(1).getStringCellValue()); return "GAYS" + "_" + row.getRowNum(); case "21": proNameList.add(row.getCell(1).getStringCellValue()); return "DANS" + "_" + row.getRowNum(); } } else { return ""; } return null; } private static void setExcleTString(int j, Row row) { for (int i = 0; i < j; i++) { if (row.getCell(i) != null) { row.getCell(i).setCellType(CellType.STRING); } } } }