Преглед изворни кода

导入商品支持wps中嵌入图片

yuanliang пре 1 година
родитељ
комит
63947c68f1

+ 14 - 11
mec-biz/src/main/java/com/ym/mec/biz/service/impl/GoodsServiceImpl.java

@@ -614,6 +614,7 @@ public class GoodsServiceImpl extends BaseServiceImpl<Integer, Goods>  implement
 		List<String> errList = new ArrayList<>();
 //		Map<String, List<Map<String, Object>>> sheetsListMap = POIUtil.importExcel(new ByteArrayInputStream(file.getBytes()), 2, file.getOriginalFilename());
 		Map<String, List<Map<String, Object>>> sheetsListMap = POIUtil.importExcel(excel, 2);
+		excel.deleteOnExit();
 		if (sheetsListMap.values().isEmpty()) {
 			errList.add("excel未解析到数据");
 			return getExportErrLogFile(errList);
@@ -857,17 +858,19 @@ public class GoodsServiceImpl extends BaseServiceImpl<Integer, Goods>  implement
 					lineErrList.add("可售分部至少需要填写一个");
 				}
 				// 校验子商品sku是否重复
-				String tempSn = objectMap.get("sn").toString();
-				String tempSku = objectMap.get("sku").toString();
-				byte[] images = objectMap.getBytes("image");
-				snImageMap.put(tempSn, images);
-				if (StringUtils.isNotEmpty(tempSn) && StringUtils.isNotEmpty(tempSku)) {
-					Set<String> set = snSubGoodsMap.getOrDefault(tempSn, new HashSet<>());
-					if (set.contains(tempSku)) {
-						lineErrList.add("子商品SKU重复");
-					} else {
-						set.add(tempSku);
-						snSubGoodsMap.put(tempSn, set);
+				String tempSn = objectMap.getOrDefault("sn", "").toString();
+				String tempSku = objectMap.getOrDefault("sku", "").toString();
+				if (StringUtils.isNotEmpty(tempSn)) {
+					byte[] images = objectMap.getBytes("image");
+					snImageMap.put(tempSn, images);
+					if (StringUtils.isNotEmpty(tempSku)) {
+						Set<String> set = snSubGoodsMap.getOrDefault(tempSn, new HashSet<>());
+						if (set.contains(tempSku)) {
+							lineErrList.add("子商品SKU重复");
+						} else {
+							set.add(tempSku);
+							snSubGoodsMap.put(tempSn, set);
+						}
 					}
 				}
 

+ 4 - 4
mec-biz/src/main/resources/config/mybatis/GoodsMapper.xml

@@ -368,7 +368,7 @@
             <if test="replacementShowOrganId!=null and replacementShowOrganId!=''">
                 AND INTE_ARRAY(#{replacementShowOrganId},g.replacement_show_organ_id_)
             </if>
-            <if test="brandId != null and brandId != ''">
+            <if test="brandId != null">
                 AND g.brand_ = #{brandId}
             </if>
             <if test="noOrganSearch == null">
@@ -386,13 +386,13 @@
                 AND (g.sn_=#{search} OR g.id_=#{search} OR g.name_ LIKE CONCAT('%', #{search}, '%'))
             </if>
             <if test="name != null and name != ''">
-                AND t.name_ like CONCAT('%', #{name}, '%'))
+                AND g.name_ like CONCAT('%', #{name}, '%')
             </if>
             <if test="sn != null and sn != ''">
-                AND t.sn_ like CONCAT('%', #{sn}, '%'))
+                AND g.sn_ like CONCAT('%', #{sn}, '%')
             </if>
             <if test="groupGoods != null">
-                AND t.group_goods_ = #{groupGoods}
+                AND g.group_goods_ = #{groupGoods}
             </if>
         </where>
     </sql>

+ 5 - 0
mec-util/pom.xml

@@ -101,5 +101,10 @@
 			<artifactId>spring-expression</artifactId>
 			<version>5.1.18.RELEASE</version>
 		</dependency>
+		<dependency>
+			<groupId>dom4j</groupId>
+			<artifactId>dom4j</artifactId>
+			<version>1.6.1</version>
+		</dependency>
 	</dependencies>
 </project>

+ 139 - 4
mec-util/src/main/java/com/ym/mec/util/excel/POIUtil.java

@@ -1,5 +1,6 @@
 package com.ym.mec.util.excel;
 
+import java.awt.image.BufferedImage;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
@@ -14,9 +15,13 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+import java.util.zip.ZipInputStream;
 
 import org.apache.commons.beanutils.NestedNullException;
 import org.apache.commons.beanutils.PropertyUtils;
+import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.poi.POIXMLDocumentPart;
 import org.apache.poi.hssf.usermodel.HSSFCell;
@@ -45,6 +50,9 @@ import org.apache.poi.xssf.usermodel.XSSFPicture;
 import org.apache.poi.xssf.usermodel.XSSFShape;
 import org.apache.poi.xssf.usermodel.XSSFSheet;
 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.dom4j.Document;
+import org.dom4j.Element;
+import org.dom4j.io.SAXReader;
 import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -54,6 +62,8 @@ import org.springframework.expression.spel.support.StandardEvaluationContext;
 
 import com.ym.mec.util.exception.UtilException;
 
+import javax.imageio.ImageIO;
+
 public class POIUtil {
 
 	private final static Logger LOGGER = LoggerFactory.getLogger(POIUtil.class);
@@ -467,9 +477,16 @@ public class POIUtil {
 			fis.close();
 			throw new UtilException("excel文件的扩展名是.xls or .xlsx!");
 		}
+		String absolutePath = excelFile.getAbsolutePath();
 		String ext = excelFile.getName().substring(index).toLowerCase();
+		// 处理WPS嵌入的图片
+		Map<String, String> codeRidMap = new HashMap<>();
+		Map<String, String> ridImgMap = new HashMap<>();
 		try {
 			if (".xlsx".equals(ext.toLowerCase())) {
+				// 处理WPS中图片问题
+				codeRidMap.putAll(ridWithIDRelationShip(absolutePath));
+				ridImgMap.putAll(ridWithImagePathRelationShip(absolutePath));
 				// 支持excel2007 xlsx格式
 				workbook = new XSSFWorkbook(fis);
 			} else if (".xls".equals(ext)) {
@@ -501,6 +518,12 @@ public class POIUtil {
 			currentRowNum = 0;
 			// 顺序取sheet
 			sheet = workbook.getSheetAt(i);
+			Map<String, List<PictureData>> picMap = null;
+			if(sheet instanceof  XSSFSheet){
+				picMap = getXlsxPictures((XSSFSheet) sheet);
+			}else if(sheet instanceof  HSSFSheet){
+				picMap = getXlsPictures((HSSFSheet) sheet);
+			}
 			List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
 			rowIter = sheet.iterator();
 			while (rowIter.hasNext()) {
@@ -536,12 +559,43 @@ public class POIUtil {
 					currentCellNum = 0;
 					while (cellIter.hasNext()) {
 						cell = cellIter.next();
-						cell.setCellType(Cell.CELL_TYPE_STRING);
-						String fieldValue = cell.getStringCellValue();
-						obj.put(fieldsName[currentCellNum], fieldValue);
-						currentCellNum++;
+
+						if(cell.getCellType() == Cell.CELL_TYPE_FORMULA){
+							Object fieldValue = "";
+							if(cell.getStringCellValue().contains("DISPIMG")){
+								String value = cell.getStringCellValue();
+								String imageId = value.substring(value.indexOf("ID_") + 3, value.lastIndexOf("\""));
+								String rid = codeRidMap.get(imageId);
+								String picPath = ridImgMap.get(rid);
+								InputStream picInputStream = openZipFile(absolutePath,"xl/" + picPath);
+								if (picInputStream != null) {
+									fieldValue= IOUtils.toByteArray(picInputStream);
+								}
+							}else {
+								fieldValue = cell.getStringCellValue();
+							}
+							obj.put(fieldsName[currentCellNum], fieldValue);
+						}else {
+							cell.setCellType(Cell.CELL_TYPE_STRING);
+							String fieldValue = cell.getStringCellValue();
+							obj.put(fieldsName[currentCellNum], fieldValue);
+							currentCellNum++;
+						}
+					}
+				}
+
+				if (picMap != null) {
+					for (Entry<String, List<PictureData>> pics : picMap.entrySet()) {
+						String key = pics.getKey();
+						String[] split = key.split("-");
+						int rowIndex = Integer.parseInt(split[0]);
+						int cellIndex = Integer.parseInt(split[1]);
+						if (rowIndex != (currentRowNum - 1)) continue;
+						obj.put(fieldsName[cellIndex], pics.getValue());
 					}
 				}
+
+
 				if (obj != null)
 					datas.add(obj);
 
@@ -989,4 +1043,85 @@ public class POIUtil {
 		return workbook;
 	}
 
+
+	 // 解析WPS中的图片,WPS中的图片和office中图片存储方式不一致
+	 private static Map<String, String> ridWithIDRelationShip(String path) {
+		 Map<String, String> imageIdMappingMap = new HashMap<>();
+		 try (InputStream inputStream = openZipFile(path, "xl/cellimages.xml")) {
+			 //读取关系xml文件
+			 // 创建SAXReader对象
+			 SAXReader reader = new SAXReader();
+			 // 加载xml文件
+			 Document dc = reader.read(inputStream);
+			 // 获取根节点
+			 Element rootElement = dc.getRootElement();
+			 //获取子节点 每一个图片节点
+			 List<Element> cellImageList = rootElement.elements();
+
+			 //循环处理每一个图片
+			 for (Element cellImage : cellImageList) {
+				 Element pic = cellImage.element("pic");
+				 Element nvPicPr = pic.element("nvPicPr");
+				 Element cNvPr = nvPicPr.element("cNvPr");
+				 //图片id
+				 String imageId = cNvPr.attribute("name").getValue().replace("ID_", "");
+//                        imageId = subImageId(imageId);
+				 Element blipFill = pic.element("blipFill");
+				 Element blip = blipFill.element("blip");
+				 //图片Rid
+				 String imageRid = blip.attribute("embed").getValue();
+				 //存入map中
+				 imageIdMappingMap.put(imageId, imageRid);
+			 }
+		 } catch (Exception e) {
+			 LOGGER.error("解析excel失败:{}", e.getMessage());
+		 }
+		 return imageIdMappingMap;
+	 }
+
+	private static Map<String, String> ridWithImagePathRelationShip(String path) {
+		Map<String, String> imageMap = new HashMap<>();
+		try (InputStream inputStream = openZipFile(path, "xl/_rels/cellimages.xml.rels")) {
+			//读取关系文件
+			// 创建SAXReader对象
+			SAXReader reader = new SAXReader();
+			// 加载xml文件
+			Document dc = reader.read(inputStream);
+			// 获取根节点
+			Element rootElement = dc.getRootElement();
+
+			List<Element> imageRelationshipList = rootElement.elements();
+
+			//处理每个关系
+			for (Element imageRelationship : imageRelationshipList) {
+				String imageRid = imageRelationship.attribute("Id").getValue();
+				String imagePath = imageRelationship.attribute("Target").getValue();
+				imageMap.put(imageRid, imagePath);
+			}
+
+		} catch (Exception e) {
+			LOGGER.error("解析excel失败:{}", e.getMessage());
+		}
+		return imageMap;
+	}
+
+	private static InputStream openZipFile(String excelFilePath, String excelZipFile) {
+		try {
+			File file = new File(excelFilePath);
+			ZipFile zipFile = new ZipFile(file);
+			ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file));
+
+			ZipEntry nextEntry;
+			while ((nextEntry = zipInputStream.getNextEntry()) != null) {
+				String name = nextEntry.getName();
+				if (name.equalsIgnoreCase(excelZipFile)) {
+					return zipFile.getInputStream(nextEntry);
+				}
+			}
+		} catch (Exception e) {
+			LOGGER.error("解析excel失败:{}", e.getMessage());
+		}
+		return null;
+	}
+
 }