前端Excel自定义文件名导出

  • vue html代码

    <div>
        <a ref="exportExcel" style="display: none;"></a>
        <el-button @click="exportExcel">下载</el-button>
    </div>
    
  • vue javascript代码

    exportExcel() {
        let excelData = [
            ['', '2020-10-16', '2020-10-17', '2020-10-18', '2020-10-19', '2020-10-20'],
            ['微服务调用次数', 123, 12, 123, 34, 423]
        ]
        let _text = ''
        excelData.forEach(rowData => {
            let rowStr = '<tr>'
            rowData.forEach(val => {
                rowStr += `<td>${val + '/t'}</td>`
            })
            rowStr = '</tr>'
            _text += rowStr
        })
        const sheetName = 'sheet'
        const uri = 'data:application/vnd.ms-excel;base64,';
        const template =
            `<html xmlns:o="urn:schemas-microsoft-com:office:office"
                xmlns:x="urn:schemas-microsoft-com:office:excel"
                xmlns="http://www.w3.org/TR/REC-html40">
            <head>
                <!--[if gte mso 9]>
                    <xml>
                        <x:ExcelWorkbook>
                            <x:ExcelWorksheets>
                                <x:ExcelWorksheet>
                                    <x:Name>${sheetName}</x:Name>
                                    <x:WorksheetOptions>
                                        <x:DisplayGridlines/>
                                    </x:WorksheetOptions>
                                </x:ExcelWorksheet>
                            </x:ExcelWorksheets>
                        </x:ExcelWorkbook>
                    </xml>
                <![endif]-->
                <meta charset="utf-8">
            </head>
            <body>
                <table>${_text}</table>
            </body>
            </html>`
        this.$refs.exportExcel.href = uri + window.btoa(unescape(encodeURIComponent(template)));
        //定义导出的文件名
        const filename = '导出的excel数据'
        this.$refs.exportExcel.download = filename
        this.$refs.exportExcel.click()
    }
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容