一、组件
<template>
<div class="m-excel-import">
<!-- 上传按钮区域 -->
<div class="m-excel-import__trigger" :style="mergedConfig.style">
<el-upload
ref="uploadRef"
class="m-excel-import__upload"
action="#"
:disabled="disabled || loading"
:before-upload="handleBeforeUpload"
:multiple="false"
:limit="1"
:accept="acceptAttr"
:show-file-list="false"
:auto-upload="true"
v-bind="$attrs"
>
<template v-if="!$slots.default" #default>
<div class="m-excel-import__button">
<m-button :config="buttonConfig">
<m-iconfont
v-if="mergedConfig.attrs.icon"
classify="m-pc-public"
icon="m-pc-public_shangc"
></m-iconfont>
{{ mergedConfig.attrs.name }}
</m-button>
</div>
</template>
<template v-else #default>
<slot></slot>
</template>
</el-upload>
<!-- 提示文案 -->
<span v-if="showTip && finalTips" class="m-excel-import__tips">{{ finalTips }}</span>
</div>
<!-- 已解析文件信息 -->
<div v-if="parsedFileName" class="m-excel-import__file">
<el-tooltip :content="parsedFileName" placement="top">
<span class="m-excel-import__file-name">{{ parsedFileName }}</span>
</el-tooltip>
<span class="m-excel-import__file-count">(共 {{ parsedData.length }} 行)</span>
<el-tooltip content="清空" placement="top">
<m-iconfont
class="m-excel-import__file-clear"
classify="m-pc-public"
icon="m-pc-public_guanbi"
@click.native.stop="handleClear"
/>
</el-tooltip>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch, type CSSProperties } from 'vue'
import type { UploadInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'
import MIconfont from '@general/components/items/icon-font/index.vue'
import MButton from '@general/components/items/button/index.vue'
// --- Types ---
/** 解析后的单行数据,key 为表头(或 columnMap 映射后的 key) */
export type ExcelRow = Record<string, any>
export interface ExcelParseResult {
/** 结构化数据(对象数组) */
rows: ExcelRow[]
/** 表头数组 */
headers: string[]
/** 总行数(不含表头) */
total: number
/** 文件名 */
fileName: string
/** 所有工作表名称 */
sheetNames: string[]
}
export interface ColumnMapItem {
/** Excel 中的表头文字 */
from: string
/** 映射为业务字段的 key */
to: string
}
export interface MExcelImportAttrs {
/** 按钮文字 */
name?: string
/** 是否显示按钮图标 */
icon?: boolean
/** 允许的文件后缀,逗号分隔 */
accept?: string
/** 文件大小上限(MB) */
fileSize?: number
/** 要读取的工作表:索引号或名称,默认第一个 */
sheet?: number | string
/** 表头所在行号(从 0 开始),默认 0 */
headerRow?: number
/** 数据起始行号(从 0 开始),默认 headerRow + 1 */
startRow?: number
/** 最大解析行数,0 表示不限制,默认 0 */
maxRows?: number
/** 表头到业务字段的映射,未配置则以原始表头作为 key */
columnMap?: ColumnMapItem[]
/** 是否跳过空行(整行为空),默认 true */
skipEmptyRow?: boolean
/** 是否将日期单元格格式化为字符串(yyyy-mm-dd),默认 true */
formatCellValue?: boolean
/** 是否禁用 */
disabled?: boolean
/** 是否显示提示文案 */
showTip?: boolean
/** 自定义提示文案,为空则自动生成 */
tips?: string
}
export interface MExcelImportProps {
config?: {
style?: CSSProperties
attrs?: MExcelImportAttrs
/** 解析完成回调,与 change 事件等效 */
event?: (result: ExcelParseResult) => void
}
}
// --- Default Config ---
const DEFAULT_CONFIG: Required<MExcelImportAttrs> = {
name: '导入Excel',
icon: false,
accept: 'xls,xlsx',
fileSize: 5,
sheet: 0,
headerRow: 0,
startRow: -1, // -1 表示自动为 headerRow + 1
maxRows: 0,
columnMap: [],
skipEmptyRow: true,
formatCellValue: true,
disabled: false,
showTip: true,
tips: '',
}
// --- Props & Emits ---
const props = withDefaults(defineProps<MExcelImportProps>(), {
config: () => ({}),
})
const emit = defineEmits<{
(e: 'change', result: ExcelParseResult): void
(e: 'success', result: ExcelParseResult): void
(e: 'error', error: Error): void
(e: 'clear'): void
(e: 'before-parse', file: File): void
}>()
// --- Refs ---
const uploadRef = ref<UploadInstance>()
const loading = ref(false)
const parsedFileName = ref('')
const parsedData = ref<ExcelRow[]>([])
// --- Merge Config ---
const mergedConfig = computed(() => {
const userAttrs = props.config?.attrs || {}
const userStyle = props.config?.style || {}
return {
style: { ...userStyle },
attrs: {
...DEFAULT_CONFIG,
...userAttrs,
} as Required<MExcelImportAttrs>,
}
})
const disabled = computed(() => mergedConfig.value.attrs.disabled)
const showTip = computed(() => mergedConfig.value.attrs.showTip)
const tips = computed(() => mergedConfig.value.attrs.tips)
const fileSize = computed(() => mergedConfig.value.attrs.fileSize)
const formattedAccept = computed(() => {
return mergedConfig.value.attrs.accept
.split(',')
.map(ext => ext.trim())
.filter(Boolean)
.join(',')
})
// 用于 el-upload accept 属性:浏览器文件选择框过滤需要带前导点的扩展名(如 .xls,.xlsx)
const acceptAttr = computed(() => {
return mergedConfig.value.attrs.accept
.split(',')
.map(ext => ext.trim().toLowerCase())
.filter(Boolean)
.map(ext => (ext.startsWith('.') ? ext : `.${ext}`))
.join(',')
})
const finalTips = computed(() => {
if (tips.value) return tips.value
return `支持${formattedAccept.value}格式,文件不超过${fileSize.value}M`
})
// 传给 m-button 的配置(plain 按钮 + loading 状态)
const buttonConfig = computed(() => ({
attrs: {
plain: true,
size: 'small' as const,
type: 'default' as const,
loading: loading.value,
disabled: disabled.value,
},
}))
// --- Helper: 判断整行是否为空 ---
const isEmptyRow = (row: any[]): boolean => {
if (!row || row.length === 0) return true
return row.every(cell => {
return cell === null || cell === undefined || String(cell).trim() === ''
})
}
// --- Helper: 单元格值格式化 ---
const normalizeCellValue = (value: any, formatCell: boolean): any => {
if (value === null || value === undefined) return ''
// xlsx 日期类型在 cell.t === 'd' 时是 Date 对象;开启格式化后转为 yyyy-mm-dd
if (formatCell && value instanceof Date) {
const y = value.getFullYear()
const m = String(value.getMonth() + 1).padStart(2, '0')
const d = String(value.getDate()).padStart(2, '0')
const hh = String(value.getHours()).padStart(2, '0')
const mm = String(value.getMinutes()).padStart(2, '0')
// 如果有时分秒则保留,否则只输出日期
if (hh !== '00' || mm !== '00') {
return `${y}-${m}-${d} ${hh}:${mm}`
}
return `${y}-${m}-${d}`
}
return value
}
// --- 核心:解析 Excel ---
const parseWorkbook = (workbook: XLSX.WorkBook, fileName: string): ExcelParseResult => {
const attrs = mergedConfig.value.attrs
const sheetNames = workbook.SheetNames
let targetName: string
if (typeof attrs.sheet === 'number') {
targetName = sheetNames[attrs.sheet] || sheetNames[0]
} else if (typeof attrs.sheet === 'string' && attrs.sheet) {
targetName = sheetNames.includes(attrs.sheet) ? attrs.sheet : sheetNames[0]
} else {
targetName = sheetNames[0]
}
if (!targetName) {
throw new Error('Excel 文件中没有可读取的工作表')
}
const worksheet = workbook.Sheets[targetName]
// header:1 -> 返回二维数组,方便自定义表头行处理
const matrix = XLSX.utils.sheet_to_json<any[]>(worksheet, {
header: 1,
defval: '',
blankrows: false,
raw: !attrs.formatCellValue,
})
if (!matrix || matrix.length === 0) {
return { rows: [], headers: [], total: 0, fileName, sheetNames }
}
const headerIdx = attrs.headerRow
const rawHeaders = (matrix[headerIdx] || []).map(h => String(h ?? '').trim())
// 建立列索引 -> 业务 key 映射
const mapList = attrs.columnMap || []
const colKeyList = rawHeaders.map((header, idx) => {
if (!header) return `__col_${idx}`
const matched = mapList.find(item => item.from === header)
return matched ? matched.to : header
})
const startIdx = attrs.startRow >= 0 ? attrs.startRow : headerIdx + 1
const rows: ExcelRow[] = []
for (let i = startIdx; i < matrix.length; i++) {
const rowArr = matrix[i] || []
if (attrs.skipEmptyRow && isEmptyRow(rowArr)) continue
const obj: ExcelRow = {}
colKeyList.forEach((key, colIdx) => {
obj[key] = normalizeCellValue(rowArr[colIdx], attrs.formatCellValue)
})
rows.push(obj)
if (attrs.maxRows > 0 && rows.length >= attrs.maxRows) break
}
return {
rows,
headers: rawHeaders,
total: rows.length,
fileName,
sheetNames,
}
}
const handleFile = async (file: File) => {
loading.value = true
emit('before-parse', file)
try {
const buffer = await file.arrayBuffer()
const workbook = XLSX.read(buffer, {
type: 'array',
cellDates: mergedConfig.value.attrs.formatCellValue,
})
const result = parseWorkbook(workbook, file.name)
parsedFileName.value = file.name
parsedData.value = result.rows
emit('change', result)
emit('success', result)
props.config?.event?.(result)
ElMessage.success(`解析成功,共 ${result.total} 行数据`)
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error))
console.error('Excel 解析失败:', err)
ElMessage.error(`解析失败:${err.message}`)
emit('error', err)
} finally {
loading.value = false
// 释放 el-upload 内部列表,保证同一文件可再次选择
uploadRef.value?.clearFiles()
}
}
const handleBeforeUpload = (file: File): boolean => {
const attrs = mergedConfig.value.attrs
// 格式校验
const fileExt = `.${file.name.split('.').pop()?.toLowerCase()}`
const acceptList = formattedAccept.value
.split(',')
.map(ext => ext.trim().toLowerCase())
.filter(Boolean)
.map(ext => (ext.startsWith('.') ? ext : `.${ext}`))
const isAccept = acceptList.includes(fileExt)
if (!isAccept) {
ElMessage.error(`文件只能是 ${formattedAccept.value} 格式`)
return false
}
// 大小校验
const isOverSize = file.size / 1024 / 1024 >= attrs.fileSize
if (isOverSize) {
ElMessage.error(`文件不能超过 ${attrs.fileSize}MB`)
return false
}
// 拦截自动上传,改为本地解析
handleFile(file)
return false
}
const handleClear = () => {
parsedFileName.value = ''
parsedData.value = []
uploadRef.value?.clearFiles()
emit('clear')
}
// --- Expose ---
defineExpose({
ref: uploadRef,
/** 手动解析任意 File 对象 */
parse: handleFile,
/** 清空已解析数据 */
clear: handleClear,
/** 获取当前解析出的结构化数据 */
getData: (): ExcelRow[] => parsedData.value,
})
</script>
<style lang="scss" scoped>
.m-excel-import {
display: inline-block;
&__trigger {
display: flex;
align-items: center;
}
&__upload {
display: inline-block;
:deep(.el-upload) {
outline: none;
}
button:focus {
outline: none;
}
}
&__button {
display: inline-flex;
align-items: center;
.m-iconfont {
font-size: 12px !important;
margin-right: 6px;
}
}
&__tips {
font-size: 10px;
margin-left: 10px;
color: #999;
line-height: normal;
}
&__file {
display: flex;
align-items: center;
margin-top: 4px;
padding: 0 7px;
color: #333;
background: #eee;
font-size: 11px;
border-radius: 3px;
line-height: 22px;
max-width: 260px;
&-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 150px;
}
&-count {
margin-left: 4px;
color: #999;
white-space: nowrap;
}
&-clear {
display: inline-block;
margin-left: 7px;
width: 16px;
height: 16px;
line-height: 16px;
text-align: center;
color: #999;
font-size: 10px !important;
border-radius: 11px;
cursor: pointer;
&:hover {
color: #fff;
background: #f43430;
}
}
}
}
</style>
二、页面调用
<!-- Excel 导入解析示例 -->
<template>
<div class="excel-import-demo">
<h2>Excel 导入解析示例</h2>
<!-- 基本用法:解析结果通过 @change 回传 -->
<div class="demo-block">
<h3>1. 基本导入(表头作为 key)</h3>
<m-excel-import :config="basicConfig" @change="handleChange" @error="handleError" />
</div>
<!-- 字段映射用法:中文表头 -> 业务字段 -->
<div class="demo-block">
<h3>2. 表头映射为业务字段</h3>
<m-excel-import :config="mappedConfig" @change="handleMappedChange" />
</div>
<!-- 解析结果表格展示 -->
<div class="demo-block">
<h3>解析结果(共 {{ tableData.length }} 行)</h3>
<el-table :data="tableData" border stripe height="320" style="width: 100%">
<el-table-column
v-for="col in tableColumns"
:key="col"
:prop="col"
:label="col"
show-overflow-tooltip
min-width="120"
/>
<template #empty>
<span style="color: #999">暂无数据,请先选择 Excel 文件</span>
</template>
</el-table>
</div>
<!-- 原始 JSON 预览 -->
<div class="demo-block">
<h3>结构化数据(JSON)</h3>
<pre class="json-preview">{{ JSON.stringify(tableData, null, 2) || '[]' }}</pre>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
// 表格展示的数据与列
const tableData = ref<Record<string, any>[]>([])
const tableColumns = ref<string[]>([])
// 1. 基本配置:使用默认表头行作为 key
const basicConfig = {
attrs: {
name: '导入Excel',
icon: true,
accept: 'xls,xlsx',
fileSize: 10,
headerRow: 0,
showTip: true,
},
}
// 2. 字段映射配置:把中文表头映射为业务字段 key
const mappedConfig = {
attrs: {
name: '导入(字段映射)',
icon: true,
accept: 'xls,xlsx',
fileSize: 10,
headerRow: 0,
// 表头「姓名/手机号/部门」映射为 name/phone/dept
columnMap: [
{ from: '姓名', to: 'name' },
{ from: '手机号', to: 'phone' },
{ from: '部门', to: 'dept' },
],
tips: '第一行为表头,需包含:姓名、手机号、部门',
},
event: (result: any) => {
console.log('config.event 回调:', result)
},
}
// 基本导入回调
const handleChange = (result: any) => {
console.log('解析结果:', result)
tableData.value = result.rows
tableColumns.value = result.rows.length ? Object.keys(result.rows[0]) : []
ElMessage.success(`解析成功:${result.fileName},${result.total} 行`)
}
// 字段映射回调
const handleMappedChange = (result: any) => {
console.log('映射解析结果:', result)
tableData.value = result.rows
tableColumns.value = result.rows.length ? Object.keys(result.rows[0]) : []
}
const handleError = (err: Error) => {
console.error('解析出错:', err)
}
</script>
<style scoped>
.excel-import-demo {
padding: 20px;
}
.demo-block {
margin-bottom: 24px;
}
.demo-block h3 {
font-size: 14px;
margin-bottom: 10px;
color: #333;
}
.json-preview {
padding: 10px;
background: #f5f5f5;
border-radius: 4px;
max-height: 300px;
overflow: auto;
font-size: 12px;
}
</style>
三、页面验证
需要的数据都有了,效果不错
