Vue 纯前端 Excel表格一键导入技巧
·
一、导入按钮
import * as XLSX from 'xlsx'
<a-upload
:before-upload="beforeUpload"
:show-upload-list="false"
accept=".xlsx,.xls"
>
<a-button type="primary" size="small">
导入表格
</a-button>
</a-upload>
二、表格导入前的验证
// 文件上传前校验
beforeUpload(file) {
// 校验文件类型
const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
file.type === 'application/vnd.ms-excel';
if (!isExcel) {
this.$message.error('请上传Excel格式文件');
return false;
}
// 校验文件大小
const isWithinSizeLimit = file.size / 1024 / 1024 < 10;
if (!isWithinSizeLimit) {
this.$message.error('文件大小需小于10MB');
return false;
}
// 校验通过后执行导入
this.handleExcelImport(file);
}
三、 处理Excel导入
// Excel文件导入处理
handleExcelImport(file) {
const reader = new FileReader();
reader.onload = (e) => {
try {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: 'array' });
const firstSheet = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheet];
const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
this.parseExcelData(jsonData);
} catch (error) {
this.$message.error('表格解析失败,请检查文件格式!');
console.error('Excel解析错误:', error);
}
};
reader.readAsArrayBuffer(file);
},
四、 处理Excel导入
// Excel数据解析
parseExcelData(data) {
if (!data || data.length < 2) {
this.$message.error('表格数据为空或格式不正确!')
return
}
// 提取表头和内容行
const headers = data[0]
const rows = data.slice(1)
// 校验关键列是否存在
const dateColumnIndex = this.findColumnIndex(headers, ['日期', 'date', '时间'])
const flowNumColumnIndex = this.findColumnIndex(headers, ['引流量', 'flow', '流量', 'num'])
if (dateColumnIndex === -1 || flowNumColumnIndex === -1) {
this.$message.error('表格格式不正确!请确保包含"日期"和"引流量"列')
return
}
const importedData = []
let successCount = 0
let errorCount = 0
rows.forEach((row, index) => {
if (row.length === 0) return // 跳过空行
const dateValue = row[dateColumnIndex]
const flowNumValue = row[flowNumColumnIndex]
// 数据校验
if (this.validateRowData(dateValue, flowNumValue, index + 2)) {
const formattedDate = this.formatDate(dateValue)
if (formattedDate) {
importedData.push({
flowDate: formattedDate,
flowNum: Number(flowNumValue),
itemId: this.id
})
successCount++
} else {
errorCount++
}
} else {
errorCount++
}
})
// 处理导入结果
if (importedData.length > 0) {
this.form.dataval = [...importedData]
this.$message.success(`导入成功!成功导入${successCount}条数据${errorCount > 0 ? `,${errorCount}条数据格式错误已跳过` : ''}`)
} else {
this.$message.error('没有有效的数据可以导入!')
}
},
更多推荐

所有评论(0)