diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportTaskProcessorServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportTaskProcessorServiceImpl.java index 572cfad9..6fdad804 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportTaskProcessorServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportTaskProcessorServiceImpl.java @@ -148,6 +148,9 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic String storagePath = fileInfo.getStoragePath(); String storageType = fileInfo.getStorageType(); + String filename = fileInfo.getFilename(); + boolean isExcel = filename != null && (filename.toLowerCase().endsWith(".xlsx") || filename.toLowerCase().endsWith(".xls")); + String fileExt = isExcel ? (filename.toLowerCase().endsWith(".xlsx") ? ".xlsx" : ".xls") : ".csv"; InputStream fileInputStream; if ("local".equals(storageType)) { @@ -158,7 +161,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic fileInputStream = new java.io.BufferedInputStream(new java.io.FileInputStream(localFile)); csvFile = localFile; } else { - tempOssFile = java.io.File.createTempFile("import-csv-", ".csv"); + tempOssFile = java.io.File.createTempFile("import-file-", fileExt); if (!ossService.downloadFile(storagePath, tempOssFile)) { throw new BusinessException("从对象存储下载文件失败,storagePath: " + storagePath); } @@ -166,7 +169,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic fileInputStream = new java.io.BufferedInputStream(new java.io.FileInputStream(tempOssFile)); } - Charset charset = detectFileEncoding(fileInputStream); + Charset charset = isExcel ? java.nio.charset.StandardCharsets.UTF_8 : detectFileEncoding(fileInputStream); ImportRuntimeContext context = new ImportRuntimeContext(task.getCompanyId(), task.getShopId(), task.getCreateBy(), task.getId()); java.util.function.BiConsumer progressCallback = (total, done) -> { @@ -175,10 +178,16 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic notifyTaskProgress(task.getCreateBy(), convertToVO(updatedTask)); }; - // 将 csvFile 传给 task(临时方案:task 本身没有此字段,由 process 方法内部读取) - final File finalCsvFile = csvFile; - ImportRuntimeContext.ImportResult result = orderImportProcessor.process( - task, finalCsvFile, charset, fieldMapping, statusMapping, context, progressCallback); + // 根据文件类型路由到对应解析器 + final File finalImportFile = csvFile; + ImportRuntimeContext.ImportResult result; + if (isExcel) { + result = orderImportProcessor.processExcel( + task, finalImportFile, fieldMapping, statusMapping, context, progressCallback); + } else { + result = orderImportProcessor.process( + task, finalImportFile, charset, fieldMapping, statusMapping, context, progressCallback); + } String finalStatus = result.failCount == 0 ? "success" : (result.insertCount > 0 ? "success" : "failed"); String summary = String.format( diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/OrderImportProcessor.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/OrderImportProcessor.java index cd37a6bd..82e80526 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/OrderImportProcessor.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/OrderImportProcessor.java @@ -33,6 +33,10 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import java.io.IOException; /** * 订单导入核心处理器(并行版本) @@ -70,10 +74,40 @@ public class OrderImportProcessor { /** * 队列元素:原始 CSV 行数据(由主线程解析出,传递给 workers) */ + /** Excel 行数据包装器(用于替代 CSVRecord) */ + public static class ExcelRow { + private final Map rowData; + private final List orderedHeaders; + + public ExcelRow(Map rowData, List orderedHeaders) { + this.rowData = rowData; + this.orderedHeaders = orderedHeaders; + } + + public String get(String header) { + if (header == null) return null; + String v = rowData.get(header); + if (v != null) return v; + String normalized = normalizeHeader(header); + for (Map.Entry e : rowData.entrySet()) { + if (normalizeHeader(e.getKey()).equals(normalized)) { + return e.getValue(); + } + } + return null; + } + + public boolean isEmpty(String header) { + String v = get(header); + return v == null || v.trim().isEmpty(); + } + } + public static class PendingRow { public final int rowNumber; - public final CSVRecord record; - public final CreateOrderDTO dto; // 主线程已解析好的 DTO + /** 原始行数据(CSV → Map via csvRecordToMap;Excel → 直接为 Map) */ + public final Map rowData; + public final CreateOrderDTO dto; public final Map fieldMapping; public final Map statusMapping; public final Long shopId; @@ -83,7 +117,7 @@ public class OrderImportProcessor { /** 无参构造器,用于毒丸(poison pill)信号 */ public PendingRow() { this.rowNumber = -1; - this.record = null; + this.rowData = null; this.dto = null; this.fieldMapping = null; this.statusMapping = null; @@ -92,12 +126,12 @@ public class OrderImportProcessor { this.createBy = null; } - public PendingRow(int rowNumber, CSVRecord record, CreateOrderDTO dto, + public PendingRow(int rowNumber, Map rowData, CreateOrderDTO dto, Map fieldMapping, Map statusMapping, Long shopId, Long companyId, Long createBy) { this.rowNumber = rowNumber; - this.record = record; + this.rowData = rowData; this.dto = dto; this.fieldMapping = fieldMapping; this.statusMapping = statusMapping; @@ -242,7 +276,8 @@ public class OrderImportProcessor { CreateOrderDTO dto = parseOrderFromCSV(record, fieldMapping, statusMapping, task.getShopId(), context.getCompanyId(), context.getCreateBy(), context); - PendingRow row = new PendingRow(rowNumber, record, dto, fieldMapping, statusMapping, + Map rowMap = csvRecordToMap(record); + PendingRow row = new PendingRow(rowNumber, rowMap, dto, fieldMapping, statusMapping, task.getShopId(), context.getCompanyId(), context.getCreateBy()); workQueue.offer(row); @@ -322,6 +357,512 @@ public class OrderImportProcessor { return result; } + // ==================== Excel 解析入口 ==================== + + /** + * 处理 Excel 订单导入(入口方法) + */ + public ImportRuntimeContext.ImportResult processExcel( + top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.po.ImportTaskPO task, + File excelFile, + Map fieldMapping, + Map statusMapping, + ImportRuntimeContext context, + BiConsumer progressCallback) { + + ImportRuntimeContext.ImportResult result = new ImportRuntimeContext.ImportResult(); + + try (FileInputStream fis = new FileInputStream(excelFile); + Workbook workbook = WorkbookFactory.create(fis)) { + + Sheet sheet = workbook.getSheetAt(0); + if (sheet == null) { + throw new BusinessException("Excel 文件中没有工作表"); + } + + // 读取表头(第一行) + Row headerRow = sheet.getRow(0); + if (headerRow == null) { + throw new BusinessException("Excel 文件表头行为空"); + } + + List orderedHeaders = new ArrayList<>(); + Map headerIndexMap = new HashMap<>(); + for (int col = 0; col < headerRow.getLastCellNum(); col++) { + Cell cell = headerRow.getCell(col); + String header = getCellStringValue(cell); + if (header != null && !header.trim().isEmpty()) { + header = header.trim(); + orderedHeaders.add(header); + headerIndexMap.put(header, col); + } + } + + // 读取数据行 + List> rowDataList = new ArrayList<>(); + for (int i = 1; i <= sheet.getLastRowNum(); i++) { + Row dataRow = sheet.getRow(i); + if (dataRow == null) continue; + Map rowMap = new LinkedHashMap<>(); + for (String header : orderedHeaders) { + Integer colIdx = headerIndexMap.get(header); + if (colIdx == null) { + rowMap.put(header, ""); + continue; + } + Cell cell = dataRow.getCell(colIdx); + String val = getCellStringValue(cell); + rowMap.put(header, val != null ? val.trim() : ""); + } + // 只要有一列有内容就认为是有效行 + boolean hasContent = rowMap.values().stream().anyMatch(v -> v != null && !v.isEmpty()); + if (hasContent) { + rowDataList.add(rowMap); + } + } + + result.totalCount = rowDataList.size(); + context.totalCount = rowDataList.size(); + context.progressCallback = progressCallback; + context.setOrderImportFieldMapping(fieldMapping); + + // 预加载数据 + ImportRuntimeContext.MappingField specCodeField = fieldMapping.get("spec_code"); + ImportRuntimeContext.MappingField productCodeField = fieldMapping.get("product_code"); + ImportRuntimeContext.MappingField linkProductNameField = fieldMapping.get("link_product_name"); + ImportRuntimeContext.MappingField orderStatusField = fieldMapping.get("status"); + ImportRuntimeContext.MappingField platformOrderNoField = fieldMapping.get("platform_order_no"); + ImportRuntimeContext.MappingField orderDateField = fieldMapping.get("order_time"); + + Set specCodes = new HashSet<>(); + Set productCodes = new HashSet<>(); + Set productNames = new HashSet<>(); + Set platformOrderNos = new HashSet<>(); + Set statusNames = new HashSet<>(); + + for (Map rowMap : rowDataList) { + context.addNormalizedValue(specCodes, getValue(rowMap, specCodeField)); + context.addNormalizedValue(productCodes, getValue(rowMap, productCodeField)); + context.addNormalizedValue(productNames, getValue(rowMap, linkProductNameField)); + context.addNormalizedValue(platformOrderNos, getValue(rowMap, platformOrderNoField)); + context.addNormalizedValue(statusNames, getValue(rowMap, orderStatusField)); + if (context.getDetectedDatePattern() == null && orderDateField != null) { + String dateStr = getValue(rowMap, orderDateField); + if (dateStr != null && !dateStr.trim().isEmpty()) { + context.setDetectedDatePattern(detectDateFormat(dateStr.trim())); + } + } + } + + specHelper.preloadProductSpecs(context, specCodes); + specHelper.preloadProductsByCode(context, productCodes); + specHelper.preloadProductsByName(context, productNames); + specHelper.preloadPlatformOrderNos(context, platformOrderNos, orderMapper); + specHelper.preloadStatuses(context, statusNames, statusMapping); + specHelper.preloadShopProductRelations(context, shopProductRelationMapper); + + // ========== 并行处理(与 CSV 共用同一套 worker 机制)========== + LinkedBlockingQueue workQueue = new LinkedBlockingQueue<>(); + List results = Collections.synchronizedList(new ArrayList<>()); + ExecutorService workerPool = Executors.newFixedThreadPool(PARALLELISM); + for (int i = 0; i < PARALLELISM; i++) { + workerPool.submit(() -> processWorkerLoopForMap(workQueue, results, context)); + } + + StringBuilder errorMessages = new StringBuilder(); + int flushedTotal = 0; + int[] flushedLast; + + for (int i = 0; i < rowDataList.size(); i++) { + Map rowMap = rowDataList.get(i); + int rowNumber = i + 2; // Excel 行号从 1 开始,减 1 是标题行,再 +1 是数据第 1 行 + + try { + CreateOrderDTO dto = parseOrderFromMap(rowMap, fieldMapping, statusMapping, + task.getShopId(), context.getCompanyId(), context.getCreateBy(), context); + + PendingRow row = new PendingRow(rowNumber, rowMap, dto, fieldMapping, statusMapping, + task.getShopId(), context.getCompanyId(), context.getCreateBy()); + workQueue.offer(row); + + queueShopProductRelation(dto, context); + if (context.pendingRelations.size() >= RELATION_BATCH_SIZE) { + flushPendingRelations(context); + } + + } catch (Exception e) { + result.failCount++; + errorMessages.append(String.format("第%d行:%s", rowNumber, e.getMessage())) + .append(System.lineSeparator()); + } + + result.failCount += drainResultsToPendingOrders(results, context, errorMessages); + if (context.pendingOrders.size() >= ORDER_BATCH_SIZE) { + flushedLast = doFlushPendingOrders(context, errorMessages); + result.insertCount += flushedLast[0]; + result.failCount += flushedLast[1]; + result.updateCount += flushedLast[2]; + result.existingUnchangedCount += flushedLast[4]; + result.updateDbFailCount += flushedLast[3]; + flushedTotal += flushedLast[0] + flushedLast[2] + flushedLast[4]; + if (progressCallback != null) { + progressCallback.accept(result.totalCount, flushedTotal); + } + } + } + + // 发送毒丸,停止 workers + for (int i = 0; i < PARALLELISM; i++) { + workQueue.offer(new PendingRow()); + } + + workerPool.shutdown(); + try { + if (!workerPool.awaitTermination(WORKER_TERMINATE_TIMEOUT_SEC, TimeUnit.SECONDS)) { + workerPool.shutdownNow(); + } + } catch (InterruptedException e) { + workerPool.shutdownNow(); + Thread.currentThread().interrupt(); + } + + result.failCount += drainResultsToPendingOrders(results, context, errorMessages); + flushedLast = doFlushPendingOrders(context, errorMessages); + result.insertCount += flushedLast[0]; + result.failCount += flushedLast[1]; + result.updateCount += flushedLast[2]; + result.existingUnchangedCount += flushedLast[4]; + result.updateDbFailCount += flushedLast[3]; + flushedTotal += flushedLast[0] + flushedLast[2] + flushedLast[4]; + flushPendingRelations(context); + + if (progressCallback != null) { + progressCallback.accept(result.totalCount, flushedTotal); + } + result.successCount = result.insertCount + result.updateCount + result.existingUnchangedCount; + result.mergedDuplicatePlatformNoCount = context.mergedDuplicatePlatformNoCount.get(); + result.errorMessages = errorMessages; + + } catch (BusinessException e) { + throw e; + } catch (Exception e) { + throw new BusinessException("Excel 解析失败: " + e.getMessage()); + } + + return result; + } + + // ==================== Worker 线程循环(Map 版本) ==================== + + private void processWorkerLoopForMap(LinkedBlockingQueue workQueue, + List results, + ImportRuntimeContext context) { + while (!Thread.currentThread().isInterrupted()) { + PendingRow row; + try { + row = workQueue.poll(100, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } + if (row == null) continue; + if (row.rowNumber < 0) break; // 毒丸 + + try { + CreateOrderDTO dto = resolveProductAndSpec(row, context); + OrderPO orderPO = buildOrderPO(dto, context.getCompanyId(), + context.getCreateBy(), context.getTaskId(), context); + + String platformOrderNo = dto.getPlatformOrderNo(); + boolean isUpdate = false; + if (platformOrderNo != null && !platformOrderNo.trim().isEmpty()) { + String normalized = platformOrderNo.trim(); + synchronized (context.pendingPlatformOrderNos) { + if (context.pendingPlatformOrderNos.contains(normalized)) { + isUpdate = true; + } + } + } + + synchronized (results) { + results.add(OrderParseResult.success(row.rowNumber, dto, orderPO, platformOrderNo, isUpdate)); + } + context.processedCount.incrementAndGet(); + + } catch (Exception e) { + synchronized (results) { + results.add(OrderParseResult.error(row.rowNumber, e)); + } + context.processedCount.incrementAndGet(); + } + } + } + + // ==================== CSVRecord → Map 转换 ==================== + + /** + * 将 CSVRecord 转换为 Map(保持顺序) + */ + private Map csvRecordToMap(CSVRecord record) { + Map map = new LinkedHashMap<>(); + if (record != null && record.getParser() != null) { + Map headerMap = record.getParser().getHeaderMap(); + if (headerMap != null) { + for (Map.Entry entry : headerMap.entrySet()) { + String header = entry.getKey(); + try { + String val = record.get(header); + map.put(header, val != null ? val.trim() : ""); + } catch (IllegalArgumentException e) { + // ignore + } + } + } + } + return map; + } + + // ==================== Map 版本的 getValue ==================== + + private String getValue(Map rowData, ImportRuntimeContext.MappingField mappingField) { + if (mappingField == null || mappingField.getFileFieldName() == null + || mappingField.getFileFieldName().trim().isEmpty()) { + return null; + } + String expectedHeader = mappingField.getFileFieldName().trim(); + return getValue(rowData, expectedHeader); + } + + private String getValue(Map rowData, String header) { + if (header == null || header.trim().isEmpty()) return null; + String val = rowData.get(header.trim()); + if (val != null && !val.trim().isEmpty()) return val.trim(); + // fallback: case-insensitive + String normalized = normalizeHeader(header); + for (Map.Entry e : rowData.entrySet()) { + if (normalizeHeader(e.getKey()).equals(normalized)) { + String v = e.getValue(); + return (v != null && !v.trim().isEmpty()) ? v.trim() : null; + } + } + return null; + } + + // ==================== Map 版本的订单解析 ==================== + + CreateOrderDTO parseOrderFromMap(Map rowData, + Map fieldMapping, + Map statusMapping, + Long shopId, Long companyId, Long createBy, + ImportRuntimeContext context) { + CreateOrderDTO dto = new CreateOrderDTO(); + dto.setShopId(shopId); + + ImportRuntimeContext.MappingField platformOrderNoField = fieldMapping.get("platform_order_no"); + if (platformOrderNoField != null) { + String pon = getValue(rowData, platformOrderNoField); + if (pon != null && !pon.trim().isEmpty()) { + dto.setPlatformOrderNo(pon.trim()); + } + } + + ImportRuntimeContext.MappingField statusField = fieldMapping.get("status"); + if (statusField != null) { + String statusStr = getValue(rowData, statusField); + if (statusStr != null && !statusStr.trim().isEmpty()) { + Long statusId = statusMapping.get(statusStr.trim()); + if (statusId != null) { + dto.setStatusId(statusId); + } else { + Long id = specHelper.findOrderStatusIdByName( + context.getCompanyId(), statusStr, context); + if (id != null) { + dto.setStatusId(id); + } else { + id = specHelper.createOrderStatusIfNotExists( + context.getCompanyId(), statusStr, createBy, context); + dto.setStatusId(id); + } + } + } + } + + ImportRuntimeContext.MappingField specCodeField = fieldMapping.get("spec_code"); + ImportRuntimeContext.MappingField productCodeField = fieldMapping.get("product_code"); + ImportRuntimeContext.MappingField linkProductNameField = fieldMapping.get("link_product_name"); + ImportRuntimeContext.MappingField quantityField = fieldMapping.get("product_quantity"); + ImportRuntimeContext.MappingField unitPriceField = fieldMapping.get("unit_price"); + ImportRuntimeContext.MappingField productCostField = fieldMapping.get("product_cost"); + ImportRuntimeContext.MappingField shippingCostField = fieldMapping.get("shipping_cost"); + ImportRuntimeContext.MappingField otherCostField = fieldMapping.get("other_cost"); + ImportRuntimeContext.MappingField receivedAmountField = fieldMapping.get("received_amount"); + ImportRuntimeContext.MappingField orderDateField = fieldMapping.get("order_time"); + + String specCode = getValue(rowData, specCodeField); + if (specCode == null || specCode.trim().isEmpty()) { + if (specCodeField == null + || (specCodeField.getRequired() != null && specCodeField.getRequired())) { + throw new BusinessException("规格编码不能为空"); + } + } + + String receivedAmountStr = getValue(rowData, receivedAmountField); + if ((receivedAmountStr == null || receivedAmountStr.trim().isEmpty()) + && receivedAmountField != null && receivedAmountField.getRequired() != null && receivedAmountField.getRequired()) { + throw new BusinessException("商家实收金额不能为空"); + } + + String productQuantityStr = getValue(rowData, quantityField); + if ((productQuantityStr == null || productQuantityStr.trim().isEmpty()) + && quantityField != null && quantityField.getRequired() != null && quantityField.getRequired()) { + throw new BusinessException("商品数量不能为空"); + } + + if (receivedAmountStr != null && !receivedAmountStr.trim().isEmpty()) { + try { + dto.setReceivedAmount(new BigDecimal(receivedAmountStr.trim())); + } catch (NumberFormatException e) { + throw new BusinessException("商家实收金额格式错误: " + receivedAmountStr); + } + } else if (receivedAmountField != null && receivedAmountField.getRequired() != null && receivedAmountField.getRequired()) { + throw new BusinessException("商家实收金额不能为空"); + } + + if (productQuantityStr != null && !productQuantityStr.trim().isEmpty()) { + try { + dto.setQuantity(Integer.parseInt(productQuantityStr.trim())); + if (dto.getQuantity() <= 0) { + throw new BusinessException("商品数量必须大于0"); + } + } catch (NumberFormatException e) { + throw new BusinessException("商品数量格式错误: " + productQuantityStr); + } + } else if (quantityField != null && quantityField.getRequired() != null && quantityField.getRequired()) { + throw new BusinessException("商品数量不能为空"); + } + + String productCode = getValue(rowData, productCodeField); + if (productCode != null && productCode.trim().isEmpty()) productCode = null; + String linkProductName = getValue(rowData, linkProductNameField); + if (linkProductName != null) { + linkProductName = linkProductName.trim(); + if (linkProductName.isEmpty()) linkProductName = null; + } + String linkSpecName = getValue(rowData, fieldMapping.get("link_spec_name")); + if (linkSpecName != null) { + linkSpecName = linkSpecName.trim(); + if (linkSpecName.isEmpty()) linkSpecName = null; + } + + dto.setLinkProductName(linkProductName); + dto.setLinkSpecName(linkSpecName); + + if (quantityField != null) { + String qtyStr = getValue(rowData, quantityField); + if (qtyStr != null && !qtyStr.trim().isEmpty()) { + try { + dto.setQuantity(Integer.parseInt(qtyStr.trim())); + } catch (NumberFormatException e) { + throw new BusinessException("数量格式错误: " + qtyStr); + } + } + } + + if (unitPriceField != null) { + String priceStr = getValue(rowData, unitPriceField); + if (priceStr != null && !priceStr.trim().isEmpty()) { + dto.setUnitPrice(new BigDecimal(priceStr.trim())); + } + } + + if (productCostField != null) { + String costStr = getValue(rowData, productCostField); + if (costStr != null && !costStr.trim().isEmpty()) { + dto.setProductCost(new BigDecimal(costStr.trim())); + } + } + + if (shippingCostField != null) { + String shippingStr = getValue(rowData, shippingCostField); + if (shippingStr != null && !shippingStr.trim().isEmpty()) { + dto.setShippingCost(new BigDecimal(shippingStr.trim())); + } + } + + if (otherCostField != null) { + String otherStr = getValue(rowData, otherCostField); + if (otherStr != null && !otherStr.trim().isEmpty()) { + dto.setOtherCost(new BigDecimal(otherStr.trim())); + } + } + + if (receivedAmountField != null) { + String receivedStr = getValue(rowData, receivedAmountField); + if (receivedStr != null && !receivedStr.trim().isEmpty()) { + dto.setReceivedAmount(new BigDecimal(receivedStr.trim())); + } + } + + if (orderDateField != null) { + String dateStr = getValue(rowData, orderDateField); + if (dateStr != null && !dateStr.trim().isEmpty()) { + LocalDateTime dateTime = parseDateTime(dateStr, context); + if (dateTime != null) { + dto.setOrderTime(dateTime); + } else { + dto.setOrderTime(LocalDateTime.now()); + } + } else { + dto.setOrderTime(LocalDateTime.now()); + } + } else { + dto.setOrderTime(LocalDateTime.now()); + } + + return dto; + } + + // ==================== Excel 单元格读取辅助 ==================== + + /** + * 将 Cell 转换为字符串(处理日期、数值等类型) + */ + private String getCellStringValue(Cell cell) { + if (cell == null) return ""; + switch (cell.getCellType()) { + case STRING: + return cell.getStringCellValue(); + case NUMERIC: + if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) { + java.util.Date date = cell.getDateCellValue(); + java.time.LocalDateTime ldt = java.time.LocalDateTime.ofInstant( + date.toInstant(), java.time.ZoneId.systemDefault()); + return ldt.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + } + double dv = cell.getNumericCellValue(); + if (dv == Math.floor(dv)) { + return String.valueOf((long) dv); + } + return String.valueOf(dv); + case BOOLEAN: + return String.valueOf(cell.getBooleanCellValue()); + case FORMULA: + try { + return cell.getStringCellValue(); + } catch (Exception e) { + try { + return String.valueOf(cell.getNumericCellValue()); + } catch (Exception ex) { + return ""; + } + } + case BLANK: + case _NONE: + default: + return ""; + } + } + // ==================== Worker 线程循环 ==================== /** @@ -396,10 +937,10 @@ public class OrderImportProcessor { if (dto.getProductSpecId() == null) { // 重新获取关键字段 - String specCodeRaw = getValue(row.record, row.fieldMapping.get("spec_code")); - String productCode = getValue(row.record, row.fieldMapping.get("product_code")); - String linkProductName = getValue(row.record, row.fieldMapping.get("link_product_name")); - String linkSpecName = getValue(row.record, row.fieldMapping.get("link_spec_name")); + String specCodeRaw = getValue(row.rowData, row.fieldMapping.get("spec_code")); + String productCode = getValue(row.rowData, row.fieldMapping.get("product_code")); + String linkProductName = getValue(row.rowData, row.fieldMapping.get("link_product_name")); + String linkSpecName = getValue(row.rowData, row.fieldMapping.get("link_spec_name")); if (specCodeRaw != null) specCodeRaw = specCodeRaw.trim(); if (productCode != null) productCode = productCode.trim().isEmpty() ? null : productCode.trim(); diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/order-import/components/FileUploadArea.vue b/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/order-import/components/FileUploadArea.vue index e44a64f9..cf8c44a5 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/order-import/components/FileUploadArea.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/order-import/components/FileUploadArea.vue @@ -33,9 +33,10 @@ const fileInputRef = ref(); // 文件验证 const validateFile = (file: File): boolean => { - const isCSV = file.type === 'text/csv' || file.name.endsWith('.csv'); - if (!isCSV) { - message.error('只能上传CSV格式的文件!'); + const ext = file.name.toLowerCase().split('.').pop() || ''; + const allowedExts = ['csv', 'xlsx', 'xls']; + if (!allowedExts.includes(ext)) { + message.error('只能上传 CSV 或 Excel 格式的文件!'); return false; } @@ -127,11 +128,11 @@ const handleFileSelect = (e: Event) => { {{ loading ? '正在解析文件,请稍候...' - : '拖拽CSV文件到此处或点击上传' + : '拖拽 CSV 或 Excel 文件到此处或点击上传' }}

- 支持.csv格式,最大10MB + 支持 .csv / .xlsx / .xls 格式,最大 10MB