mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-25 03: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);
|
||||
}
|
||||
Reference in New Issue
Block a user