mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-25 05:09:19 +08:00
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:
+7
-6
@@ -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);
|
||||
}
|
||||
@@ -117,5 +117,8 @@
|
||||
"canvas",
|
||||
"node-gyp"
|
||||
]
|
||||
},
|
||||
"dependencies": {
|
||||
"xlsx": "^0.18.5"
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+66
@@ -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: {}
|
||||
|
||||
Reference in New Issue
Block a user