一、需求:
前端無需通過后端接口,即可實現(xiàn)模板下載功能。
通過構(gòu)造一個 JSON 對象,使用前端常用的第三方庫 xlsx,可以直接將該 JSON 對象轉(zhuǎn)換成 Excel 文件,讓用戶下載模板
二、效果:
文章來源:http://www.zghlxwxcb.cn/news/detail-804431.html
三、源碼如下:文章來源地址http://www.zghlxwxcb.cn/news/detail-804431.html
npm install xlsx
<template>
<div class="download">
<el-button type="warning" @click="downloadTemplate">下載模板</el-button>
</div>
</template>
<script setup>
import * as XLSX from 'xlsx';
const writeFileAsync = (workbook, filename, options) => {
return new Promise((resolve, reject) => {
try {
XLSX.writeFile(workbook, filename, options);
resolve();
} catch (error) {
reject(error);
}
});
};
const downloadTemplate = async () => {
// 構(gòu)造json
const json = [
{
序號: '',
名稱: '',
日期: '',
地址: '',
年齡: '',
類型: '',
分?jǐn)?shù): ''
}
];
// 將json數(shù)據(jù)轉(zhuǎn)換成excel文件
const worksheet = XLSX.utils.json_to_sheet(json);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
try {
// 將excel 文件保存為blob
const blob = await writeFileAsync(workbook, '模板.xlsx', { bookType: 'xlsx', mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
if (blob instanceof Blob) {
// 創(chuàng)建下載鏈接
const url = window.URL.createObjectURL(blob);
// 創(chuàng)建隱藏的a標(biāo)簽,設(shè)置下載鏈接并觸發(fā)點(diǎn)擊
const a = document.createElement('a');
a.href = url;
a.download = 'excel.template.xlsx';
document.body.appendChild(a);
a.click();
// 釋放對象url
window.URL.revokeObjectURL(url);
// 等待5秒后關(guān)閉模態(tài)框
setTimeout(() => {
document.body.removeChild(a);
}, 5000);
} else {
throw new Error('Invalid Blob');
}
} catch (error) {
//console.error('Error creating object URL:', error);
}
};
</script>
<style lang="scss" scoped>
.download{
padding: 20px;
}
</style>
到了這里,關(guān)于#vue3 實現(xiàn)前端下載excel文件模板功能的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!