欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

前端直接導出excel文件的兩種方式

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

前言

開發(fā)中可能會有這樣的需求,本地自己生成了一個表格,此時表格并沒有上傳到后臺服務器上,所以無法通過接口進行下載,此時就需要前端自行處理了。

一、插件方式

1.插件安裝

 npm i xlsx
 npm i file-saver

2.引入

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

3.導出

         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;
		}

二、本地直接導出

1.頁面規(guī)則

  • 頁面必須要有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"), "導出表格");

總結 

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

相關文章

最新評論