在线演示地址: Excel表格解析邮件发送
xlsx是一款非常方便的只需要纯JS即可读取和导出excel的工具库,功能强大,支持格式众多。
npm install xlsx --save
<template>
<div style="margin: 10px">
<n-upload
multiple
@before-upload="onBeforeUpload" @finish="onFinish"
directory-dnd
action=""
:max="5"
>
<n-upload-dragger>
<div style="margin-bottom: 12px">
<n-icon size="48" :depth="3">
<archive-icon />
</n-icon>
</div>
<n-text style="font-size: 16px">
点击或者拖动Excel文件到该区域来上传
</n-text>
<n-p depth="3" style="margin: 8px 0 0 0">
请不要上传敏感数据,比如你的银行卡号和密码,信用卡号有效期和安全码
</n-p>
</n-upload-dragger>
</n-upload>
<n-h2 prefix="bar">
转换后内容
</n-h2>
{{fileStr}}
</div>
</template>
<script lang="ts" setup>
import {ref,computed} from 'vue';
import {read,utils} from 'xlsx';
import { ArchiveOutline as ArchiveIcon } from '@vicons/ionicons5'
const fileStr=ref('');
const isFile=ref(null);
//上传前
const onBeforeUpload = ((file: any, fileList: any) => {
return new Promise((resolve, reject) => {
isFile.value = file.file.file;
let reader = new FileReader()
reader.readAsArrayBuffer(isFile.value)
reader.onload = function () {
let buffer = reader.result as any
let bytes = new Uint8Array(buffer)
let length = bytes.byteLength
let binary = ''
for (let i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i])
}
let wb =read(binary, {
type: 'binary'
})
//解析成HTML
let outdata = utils.sheet_to_html(wb.Sheets[wb.SheetNames[0]]);
// 使用正则表达式匹配table标签,并添加样式
fileStr.value=outdata.replace(/<table>/, '<table style="border-collapse: collapse; width: 100.014%; height: 62.4px;" border="1">');;
console.log(outdata)
}
})
})
//上传后
const onFinish = ((file: any) => {
let data2 = (file.event?.target as XMLHttpRequest).response;
console.log(data2)
})
</script>
效果图