<template>
    <el-card header="导入导出excel">
        <el-upload
            action="/excel/upload"
            :headers="headers"
            method="post"
        >
            <el-button type="primary">上传excel</el-button>
        </el-upload>
        <el-button
            type="primary"
            @click="downloadExcel"
            >下载excel</el-button
        >
    </el-card>
</template>

<script setup lang="jsx">
import { ref } from 'vue';
import Cookies from 'js-cookie';
import axios from 'axios';

defineOptions({
    name: 'DemoImportOrExportExcel',
});

const headers = ref({
    Authorization: Cookies.get('Authorization') || '',
});

const downloadExcel = () => {
    axios({
        url: '/excel/download',
        method: 'get',
        // 重要，设置responseType为blob
        responseType: 'blob',
        headers: headers.value,
    }).then((response) => {
        const name = response.headers['content-disposition'].split(';')[1].split('=')[1];
        // 重要，类型要设置为'application/vnd.ms-excel;charset=utf-8'
        let blob = new Blob([response.data], { type: 'application/vnd.ms-excel;charset=utf-8' });
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = URL.createObjectURL(blob);
        link.setAttribute('download', name);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });
};
</script>

<style lang="scss" scoped></style>
