亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

前端直接導(dǎo)出excel文件的兩種方式

 更新時(shí)間:2025年01月06日 08:31:36   作者:庫(kù)庫(kù)的寫(xiě)代碼  
這篇文章主要介紹了兩種方法在前端實(shí)現(xiàn)本地表格導(dǎo)出功能,分別是插件方式和本地直接導(dǎo)出,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下

前言

開(kāi)發(fā)中可能會(huì)有這樣的需求,本地自己生成了一個(gè)表格,此時(shí)表格并沒(méi)有上傳到后臺(tái)服務(wù)器上,所以無(wú)法通過(guò)接口進(jìn)行下載,此時(shí)就需要前端自行處理了。

一、插件方式

1.插件安裝

 npm i xlsx
 npm i file-saver

2.引入

// index.vue文件
 import FileSaver from "file-saver"
 import XLSX from "xlsx"

3.導(dǎo)出

         exportExcel() {
			let et = XLSX.utils.table_to_book(
				//獲取table的DOM
				document.getElementById('table-contents')
			);
			let etout = XLSX.write(et, {
				bookType: 'xlsx',
				bookSST: true,
				type: 'array'
			});

			try {
				FileSaver.saveAs(
					new Blob([etout], {
						type: 'application/octet-stream'
					}),
					'XXX.xls'
				);
			} catch (e) {
				//console.log(e, etout)
			}
			console.log(etout);
			return etout;
		}

二、本地直接導(dǎo)出

1.頁(yè)面規(guī)則

  • 頁(yè)面必須要有table表格
<table border="1" cellspacing="0" id="table-parent" >
           <thead>
               <tr>
                 <th ></th>
               </tr>
           </thead>
           <tbody>
               <tr  >
                  <td></td>
               </tr>
           </tbody>     
    </table>

2.在JS中添加函數(shù)

var tableToExcel = (function() {
    var uri = 'data:application/vnd.ms-excel;base64,',
    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>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
        base64 = function(s) {
            return window.btoa(unescape(encodeURIComponent(s)))
        },
        format = function(s, c) {
            return s.replace(/{(\w+)}/g, function(m, p) {
                return c[p];
            })
        }
    return function(table, name) {
        if (!table.nodeType) table = document.getElementById(table);
        var ctx = {
            worksheet: name || 'Worksheet',
            table: table.innerHTML
        };
        window.location.href = uri + base64(format(template, ctx));
    }
})();

3.調(diào)用

tableToExcel(document.getElementById("table-parent"), "導(dǎo)出表格");

總結(jié) 

到此這篇關(guān)于前端直接導(dǎo)出excel文件的兩種方式的文章就介紹到這了,更多相關(guān)前端導(dǎo)出excel文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論