上一篇博客链接在这,我们使用vue3+ts实现了导入的功能,接下来,还是使用同一个组件(element-plus上传组件)来实现导出,在上篇博客中,我们在使用这个组件的同时写了一个下载模板的功能,接下来,这篇博客,我们就帮助大家完善下载模板的功能以及实现导出的功能。✌️✌️✌️
我们通过两个按钮来实现导入导出功能、具体模板的样式如下
具体样式,请参考上篇博客
<el-button
class="excel-btn"
size="small"
type="primary"
icon="download"
@click="downloadTemplate('导入用户模板文件.xlsx')">
点击下载
el-button>
//接口文件
export const downloadTemplate = fileName =>{
return service({
url: 'XXXX',
method: 'post',
params: {
fileName: fileName,
},
responseType: 'blob',
}).then(res => {
handleFileError(res, fileName);
});
}
const handleFileError = (res, fileName) => {
if (typeof res.data !== 'undefined') {
if (res.data.type === 'application/json') {
const reader = new FileReader();
reader.onload = function () {
const message = JSON.parse(reader.result).msg;
ElMessage({
showClose: true,
message: message,
type: 'error',
});
};
reader.readAsText(new Blob([res.data]));
}
} else {
var downloadUrl = window.URL.createObjectURL(new Blob([res]));
var a = document.createElement('a');
a.style.display = 'none';
a.href = downloadUrl;
a.download = fileName;
var event = new MouseEvent('click');
a.dispatchEvent(event);
}
};
以上就是下载模板的功能实现
<el-button
class="excel-btn"
size="small"
icon="download"
@click="handleExcelExport('用户列表.xlsx')">
导出
el-button>
const tableData = ref([]);
const handleExcelExport = fileName => {
if (!fileName || typeof fileName !== 'string') {
fileName = 'ExcelExport.xlsx';
}
exportExcel(tableData.value, fileName);
};
//接口
export const exportExcel = (tableData, fileName) => {
return service({
url: 'XXX',
method: 'post',
data: {
fileName: fileName,
infoList: tableData,
},
responseType: 'blob',
}).then(res => {
handleFileError(res, fileName);
});
};
const handleFileError = (res, fileName) => {
if (typeof res.data !== 'undefined') {
if (res.data.type === 'application/json') {
const reader = new FileReader();
reader.onload = function () {
const message = JSON.parse(reader.result).msg;
ElMessage({
showClose: true,
message: message,
type: 'error',
});
};
reader.readAsText(new Blob([res.data]));
}
} else {
var downloadUrl = window.URL.createObjectURL(new Blob([res]));
var a = document.createElement('a');
a.style.display = 'none';
a.href = downloadUrl;
a.download = fileName;
var event = new MouseEvent('click');
a.dispatchEvent(event);
}
};
这样我们就实现了导出功能,同时很多时候我们可能会遇到按需导出的需求,这是,我们只需要在接口中传递相应的参数即可。