feat: 订单导入支持 Excel 格式(.xlsx/.xls)

- 前端:新增 fileParser.ts(XLSX 库解析 Excel),FileUploadArea 支持 csv/xlsx/xls
- 后端:OrderImportProcessor.processExcel() 用 Apache POI 读取 Excel
- ImportTaskProcessorServiceImpl 根据文件扩展名路由到 CSV 或 Excel 解析器
- 修复 Excel 空行检测 bug(isEmpty 逻辑写反)
This commit is contained in:
小蟑螂
2026-04-20 20:43:18 +08:00
parent b270b7818a
commit 024d2443d6
7 changed files with 835 additions and 25 deletions
@@ -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<Integer, Integer> 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(
@@ -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<String, String> rowData;
private final List<String> orderedHeaders;
public ExcelRow(Map<String, String> rowData, List<String> 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<String, String> 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<String, String> rowData;
public final CreateOrderDTO dto;
public final Map<String, ImportRuntimeContext.MappingField> fieldMapping;
public final Map<String, Long> 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<String, String> rowData, CreateOrderDTO dto,
Map<String, ImportRuntimeContext.MappingField> fieldMapping,
Map<String, Long> 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<String, String> 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<String, ImportRuntimeContext.MappingField> fieldMapping,
Map<String, Long> statusMapping,
ImportRuntimeContext context,
BiConsumer<Integer, Integer> 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<String> orderedHeaders = new ArrayList<>();
Map<String, Integer> 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<Map<String, String>> rowDataList = new ArrayList<>();
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
Row dataRow = sheet.getRow(i);
if (dataRow == null) continue;
Map<String, String> 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<String> specCodes = new HashSet<>();
Set<String> productCodes = new HashSet<>();
Set<String> productNames = new HashSet<>();
Set<String> platformOrderNos = new HashSet<>();
Set<String> statusNames = new HashSet<>();
for (Map<String, String> 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<PendingRow> workQueue = new LinkedBlockingQueue<>();
List<OrderParseResult> 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<String, String> 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<PendingRow> workQueue,
List<OrderParseResult> 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<String, String>(保持顺序)
*/
private Map<String, String> csvRecordToMap(CSVRecord record) {
Map<String, String> map = new LinkedHashMap<>();
if (record != null && record.getParser() != null) {
Map<String, Integer> headerMap = record.getParser().getHeaderMap();
if (headerMap != null) {
for (Map.Entry<String, Integer> 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<String, String> 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<String, String> 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<String, String> 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<String, String> rowData,
Map<String, ImportRuntimeContext.MappingField> fieldMapping,
Map<String, Long> 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();
@@ -33,9 +33,10 @@ const fileInputRef = ref<HTMLInputElement>();
// 文件验证
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 文件到此处或点击上传'
}}
</p>
<p v-if="!loading" class="text-sm text-gray-500 dark:text-[hsl(240deg_5%_64.9%)]">
支持.csv格式,最大10MB
支持 .csv / .xlsx / .xls 格式,最大 10MB
</p>
</div>
<Button
@@ -147,7 +148,7 @@ const handleFileSelect = (e: Event) => {
<input
ref="fileInputRef"
type="file"
accept=".csv"
accept=".csv,.xlsx,.xls"
style="display: none"
:disabled="loading"
@change="handleFileSelect"
@@ -9,7 +9,7 @@ import { useVbenVxeGrid } from '#/adapter/vxe-table';
import CreateImportTaskModal from './components/CreateImportTaskModal.vue';
import FileUploadArea from './components/FileUploadArea.vue';
import { parseCSVToRawData } from './utils/csvParser';
import { parseFileToRawData } from './utils/fileParser';
defineOptions({ name: 'DataImport' });
@@ -143,7 +143,7 @@ watch(
const handleFileUpload = async (file: File) => {
importLoading.value = true;
try {
const result = await parseCSVToRawData(file);
const result = await parseFileToRawData(file);
if (result.errors.length > 0) {
message.warning(result.errors.join('; '));
@@ -165,7 +165,9 @@ const handleFileUpload = async (file: File) => {
calculateTableHeight();
});
message.success(`成功解析 ${result.data.length} 条数据`);
const fileExt = file.name.toLowerCase().split('.').pop() || '';
const format = ['xlsx', 'xls'].includes(fileExt) ? 'Excel' : 'CSV';
message.success(`成功解析 ${result.data.length} 条数据(${format} 格式)`);
} catch (error: any) {
message.error(`文件读取失败: ${error.message}`);
} finally {
@@ -0,0 +1,188 @@
/**
* 文件数据解析工具(支持 CSV 和 Excel)
*/
import Papa from 'papaparse';
import * as XLSX from 'xlsx';
export interface FileParseResult {
/** 解析成功的数据 */
data: any[];
/** 解析错误 */
errors: string[];
/** 表头(保持文件中的顺序) */
headers: string[];
}
function isExcelFile(filename: string): boolean {
const ext = filename.toLowerCase().split('.').pop() || '';
return ext === 'xlsx' || ext === 'xls';
}
/**
* 解析 CSV 文件为原始数据
*/
async function parseCSVFile(file: File): Promise<FileParseResult> {
const errors: string[] = [];
const data: any[] = [];
let headers: string[] = [];
// 尝试多种编码格式
const encodings = ['GBK', 'utf8', 'GB2312'];
let result: Papa.ParseResult<any> | null = null;
for (const encoding of encodings) {
try {
result = await new Promise<Papa.ParseResult<any>>((resolve, reject) => {
Papa.parse(file, {
header: true,
skipEmptyLines: true,
encoding: encoding as any,
complete: (results) => {
resolve(results);
},
error: (error) => {
reject(error);
},
});
});
// 检查是否成功解析出中文内容
if (result.data && result.data.length > 0) {
const firstRow = result.data[0];
const hasChineseContent = Object.values(firstRow).some(
(value) => typeof value === 'string' && /[\u4E00-\u9FA5]/.test(value),
);
if (hasChineseContent) {
break;
}
}
} catch {
continue;
}
}
if (!result) {
errors.push('无法解析 CSV 文件,请检查文件格式和编码');
return { data, errors, headers };
}
if (result.errors.length > 0) {
errors.push(
`CSV 解析错误: ${result.errors.map((e) => e.message).join(', ')}`,
);
}
if (!result.data || result.data.length === 0) {
errors.push('CSV 文件为空或没有有效数据');
return { data, errors, headers };
}
headers = result.meta.fields || [];
data.push(...result.data);
return { data, errors, headers };
}
/**
* 解析 Excel 文件为原始数据
*/
async function parseExcelFile(file: File): Promise<FileParseResult> {
const errors: string[] = [];
const data: any[] = [];
let headers: string[] = [];
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => {
try {
const arrayBuffer = e.target?.result;
if (!arrayBuffer) {
errors.push('Excel 文件读取失败');
resolve({ data, errors, headers });
return;
}
const workbook = XLSX.read(arrayBuffer, { type: 'array', cellDates: true });
// 默认取第一个 sheet
const sheetName = workbook.SheetNames[0];
if (!sheetName) {
errors.push('Excel 文件中没有工作表');
resolve({ data, errors, headers });
return;
}
const sheet = workbook.Sheets[sheetName];
// 转换为 JSON(header: 1 表示第一行作为表头)
const jsonData = XLSX.utils.sheet_to_json(sheet, {
header: 1,
defval: '',
blankrows: false,
}) as any[][];
if (jsonData.length === 0) {
errors.push('Excel 文件为空或没有有效数据');
resolve({ data, errors, headers });
return;
}
// 第一行是表头
headers = (jsonData[0] || []).map((h) => String(h ?? '').trim());
// 其余行是数据
for (let i = 1; i < jsonData.length; i++) {
const row = jsonData[i];
if (!row || row.every((cell) => cell === '' || cell == null)) {
continue; // 跳过空行
}
const rowData: Record<string, any> = {};
headers.forEach((header, idx) => {
let value = row[idx];
// XLSX 读取日期会返回 Date 对象,转成字符串
if (value instanceof Date) {
const y = value.getFullYear();
const m = String(value.getMonth() + 1).padStart(2, '0');
const d = String(value.getDate()).padStart(2, '0');
value = `${y}-${m}-${d}`;
}
rowData[header] = value != null ? String(value).trim() : '';
});
data.push(rowData);
}
resolve({ data, errors, headers });
} catch (err: any) {
errors.push(`Excel 解析失败: ${err?.message || '未知错误'}`);
resolve({ data, errors, headers });
}
};
reader.onerror = () => {
errors.push('Excel 文件读取失败');
resolve({ data, errors, headers });
};
reader.readAsArrayBuffer(file);
});
}
/**
* 解析文件为原始数据(自动根据扩展名选择解析器)
*/
export async function parseFileToRawData(file: File): Promise<FileParseResult> {
if (isExcelFile(file.name)) {
return parseExcelFile(file);
}
return parseCSVFile(file);
}
/**
* @deprecated 请使用 parseFileToRawData
*/
export async function parseCSVToRawData(file: File): Promise<FileParseResult> {
return parseCSVFile(file);
}
+3
View File
@@ -117,5 +117,8 @@
"canvas",
"node-gyp"
]
},
"dependencies": {
"xlsx": "^0.18.5"
}
}
+66
View File
@@ -498,6 +498,10 @@ overrides:
importers:
.:
dependencies:
xlsx:
specifier: ^0.18.5
version: 0.18.5
devDependencies:
'@changesets/changelog-github':
specifier: 'catalog:'
@@ -4522,6 +4526,10 @@ packages:
engines: {node: '>=0.4.0'}
hasBin: true
adler-32@1.3.1:
resolution: {integrity: sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==}
engines: {node: '>=0.8'}
agent-base@6.0.2:
resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==}
engines: {node: '>= 6.0.0'}
@@ -4880,6 +4888,10 @@ packages:
caniuse-lite@1.0.30001726:
resolution: {integrity: sha512-VQAUIUzBiZ/UnlM28fSp2CRF3ivUn1BWEvxMcVTNwpw91Py1pGbPIyIKtd+tzct9C3ouceCVdGAXxZOpZAsgdw==}
cfb@1.2.2:
resolution: {integrity: sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==}
engines: {node: '>=0.8'}
chai@5.2.0:
resolution: {integrity: sha512-mCuXncKXk5iCLhfhwTc0izo0gtEmpz5CtG2y8GiOINBlMVS6v8TMRc5TaLWKS6692m9+dVVfzgeVxR5UxWHTYw==}
engines: {node: '>=12'}
@@ -5001,6 +5013,10 @@ packages:
resolution: {integrity: sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==}
engines: {node: '>=0.10.0'}
codepage@1.15.0:
resolution: {integrity: sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==}
engines: {node: '>=0.8'}
color-convert@1.9.3:
resolution: {integrity: sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==}
@@ -6222,6 +6238,10 @@ packages:
resolution: {integrity: sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==}
engines: {node: '>=12.20.0'}
frac@1.1.2:
resolution: {integrity: sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==}
engines: {node: '>=0.8'}
fraction.js@4.3.7:
resolution: {integrity: sha512-ZsDfxO51wGAXREY55a7la9LScWpwv9RxIrYABrlvOFBlH/ShPnrtsXeuUIfXKKOVicNxQ+o8JTbJvjS4M89yew==}
@@ -9127,6 +9147,10 @@ packages:
sprintf-js@1.1.3:
resolution: {integrity: sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==}
ssf@0.11.2:
resolution: {integrity: sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==}
engines: {node: '>=0.8'}
ssri@8.0.1:
resolution: {integrity: sha512-97qShzy1AiyxvPNIkLWoGua7xoQzzPjQ0HAH4B0rWKo7SZ6USuPcrUiAFrws0UH8RrbWmgq3LMTObhPIHbbBeQ==}
engines: {node: '>= 8'}
@@ -10146,10 +10170,18 @@ packages:
resolution: {integrity: sha512-DLiFIXYC5fMPxaRg832S6F5mJYvePtmO5G9v9IgUFPhXm9/GkXarH/TUrBAVzhTCzAj9anE/+GjrgXp/54nOgw==}
engines: {node: '>= 12.0.0'}
wmf@1.0.2:
resolution: {integrity: sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==}
engines: {node: '>=0.8'}
word-wrap@1.2.5:
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
engines: {node: '>=0.10.0'}
word@0.3.0:
resolution: {integrity: sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==}
engines: {node: '>=0.8'}
workbox-background-sync@7.3.0:
resolution: {integrity: sha512-PCSk3eK7Mxeuyatb22pcSx9dlgWNv3+M8PqPaYDokks8Y5/FX4soaOqj3yhAZr5k6Q5JWTOMYgaJBpbw11G9Eg==}
@@ -10233,6 +10265,11 @@ packages:
xe-utils@3.7.8:
resolution: {integrity: sha512-V/k6B/ASYir6yLYhp62DnM17po9u1N9mou/rn4if5WoFCsAO49JpCiVpkDpwCv4zxGfWmhWgzmz4FytWF+pDVw==}
xlsx@0.18.5:
resolution: {integrity: sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==}
engines: {node: '>=0.8'}
hasBin: true
xml-name-validator@4.0.0:
resolution: {integrity: sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw==}
engines: {node: '>=12'}
@@ -13540,6 +13577,8 @@ snapshots:
acorn@8.15.0: {}
adler-32@1.3.1: {}
agent-base@6.0.2:
dependencies:
debug: 4.4.1
@@ -13955,6 +13994,11 @@ snapshots:
caniuse-lite@1.0.30001726: {}
cfb@1.2.2:
dependencies:
adler-32: 1.3.1
crc-32: 1.2.2
chai@5.2.0:
dependencies:
assertion-error: 2.0.1
@@ -14109,6 +14153,8 @@ snapshots:
cluster-key-slot@1.1.2: {}
codepage@1.15.0: {}
color-convert@1.9.3:
dependencies:
color-name: 1.1.3
@@ -15503,6 +15549,8 @@ snapshots:
dependencies:
fetch-blob: 3.2.0
frac@1.1.2: {}
fraction.js@4.3.7: {}
framesync@6.1.2:
@@ -18459,6 +18507,10 @@ snapshots:
sprintf-js@1.1.3: {}
ssf@0.11.2:
dependencies:
frac: 1.1.2
ssri@8.0.1:
dependencies:
minipass: 3.3.6
@@ -19661,8 +19713,12 @@ snapshots:
triple-beam: 1.4.1
winston-transport: 4.9.0
wmf@1.0.2: {}
word-wrap@1.2.5: {}
word@0.3.0: {}
workbox-background-sync@7.3.0:
dependencies:
idb: 7.1.1
@@ -19816,6 +19872,16 @@ snapshots:
xe-utils@3.7.8: {}
xlsx@0.18.5:
dependencies:
adler-32: 1.3.1
cfb: 1.2.2
codepage: 1.15.0
crc-32: 1.2.2
ssf: 0.11.2
wmf: 1.0.2
word: 0.3.0
xml-name-validator@4.0.0: {}
y18n@4.0.3: {}