xlsx是由SheetJS开发的一个处理excel文件的npm库,适用于前端开发者实现下载模板、导入导出excel文件等需求,演示的项目的技术栈为vue3 + elementPlus
npm install xlsx
import * as XLSX from 'xlsx';
const handleDownloadTemplate = () => {
let book = XLSX.utils.book_new();
// 实例化一个Sheet
let sheet = XLSX.utils.json_to_sheet(
[
{
'姓名': '',
'年龄': ''
},
],
{
header: [
'姓名',
'年龄',
],
},
);
// 将Sheet写入工作簿
XLSX.utils.book_append_sheet(book, sheet, 'Sheet1');
// 写入文件,直接触发浏览器的下载
XLSX.writeFile(book, 'xxxx模板.xlsx');
}
const handleExportData = () => {
let data = [{}]
const rs = _.clone(formConfig.value.formData.details)
for (let k in rs[0]) {
data[0][k] = formConfig.value.tableMapKeyValue[k]
}
data = data.concat(rs);
downloadExl(data, 'xxx表')
}
const downloadExl = (json, downName, type) => { // 导出到excel
let keyMap = [] // 获取键
for (let k in json[0]) {
keyMap.push(k)
}
let tmpdata = [] // 用来保存转换好的json
const jsonTempData = json.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
v: v[k],
position: (String.fromCharCode(65 + j)) + (i + 1)
})))
jsonTempData.reduce((prev, next) => prev.concat(next)).forEach(function (v) {
tmpdata[v.position] = {
v: v.v
}
})
let outputPos = Object.keys(tmpdata) // 设置区域,比如表格从A1到D10
let tmpWB = {
SheetNames: ['mySheet'], // 保存的表标题
Sheets: {
'mySheet': Object.assign({},
tmpdata, // 内容
{
'!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] // 设置填充区域
})
}
}
let tmpDown = new Blob([s2ab(XLSX.write(tmpWB,
{bookType: (type === undefined ? 'xlsx' : type), bookSST: false, type: 'binary'} // 这里的数据是用来定义导出的格式类型
))], {
type: ''
}) // 创建二进制对象写入转换好的字节流
const elink = document.createElement('a');
elink.href = URL.createObjectURL(tmpDown) // 创建对象超链接
elink.download = downName + '.xlsx' // 下载名称
elink.click() // 模拟点击实现下载
setTimeout(function () { // 延时释放
URL.revokeObjectURL(elink.href) // 用URL.revokeObjectURL()来释放这个object URL
}, 100)
}
// 字符串转字符流
const s2ab = (s) => {
const buf = new ArrayBuffer(s.length)
const view = new Uint8Array(buf);
for (var i = 0; i !== s.length; ++i) {
view[i] = s.charCodeAt(i) & 0xFF
}
return buf
}
相关数据说明
formConfig.value.formData.details: 表格数据,格式[{name: ‘’ ",age: ‘’ "}]
formConfig.value.tableMapKeyValue[k]:
tableMapKeyValue: {
name: '姓名',
age: '年龄'
}
导入excel的核心就是解析excel表的数据,转换成我们想要的格式,诸如
[{name: 'jack',age:15}]
这样的格式
导入的组件是用到elementPlus中的el-upload组件
Html
<el-upload
ref="uploadRef"
accept=".xls, .xlsx"
:auto-upload="false"
:limit="1"
:on-exceed="OnFileExceed"
:on-change="OnFileChange"
style="margin: 0 8px"
>
<el-button type="primary" plain :loading="loading">
<el-icon v-if="!loading" class="el-icon--upload"><el-icon-upload-filled /></el-icon>
<slot>导入数据</slot>
</el-button>
</el-upload>
</template>
js
const OnFileChange = (uploadFile, _) => {
// 隐藏文件列表展示
uploadRef.value.clearFiles(['success', 'ready', 'uploading', 'fail']);
// 上传、解析excel数据
ImportExcel(uploadFile.raw);
};
function ImportExcel(filetemp) {
file.value = filetemp;
// 通过DOM取文件数据
f.value = file.value
var reader = new FileReader();
FileReader.prototype.readAsBinaryString = function(f) {
var binary = "";
var wb; //读取完成的数据
var outdata;
var reader = new FileReader();
reader.onload = function(e) {
var bytes = new Uint8Array(reader.result);
var length = bytes.byteLength;
for(var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
wb = XLSX.read(binary, {
type: 'binary'
});
outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);//outdata就是你想要的东西
this.da = [...outdata]
const arr = this.da.map((v) => {
const obj = {};
Object.entries(props.formConfig.tableMapKeyValue).forEach(([key, value]) => {
obj[key] = v[value];
});
return obj;
});
emit('uploadExcelData',arr)
return arr
}
reader.readAsArrayBuffer(f.value);
}
reader.readAsBinaryString(f);
}
其中 emit(‘uploadExcelData’,arr)中的arr就是我们想要得到的数据。