vue + xlsx实现Excel导出
简单粗暴步骤,无需花里胡哨
第一步:npm install --save xlsx@0.14.3 第二步:全局封装公共方法(或者局部定义)
import XLSX from "xlsx" ;
let common = {
install: function ( $Vue) {
let Vue = $Vue. prototype;
let common = {
exportExcel ( data, name, cols = [ ] ) {
let sheet = XLSX . utils. aoa_to_sheet ( data)
sheet[ '!cols' ] = cols
this . downExcel ( this . sheetBlob ( sheet) , name)
} ,
downExcel ( url, saveName) {
if ( typeof url === 'object' && url instanceof Blob ) {
url = URL . createObjectURL ( url)
}
let aLink = document. createElement ( 'a' )
aLink. href = url
aLink. download = saveName || ''
let event
if ( window. MouseEvent) event = new MouseEvent ( 'click' )
else {
event = document. createEvent ( 'MouseEvents' )
event. initMouseEvent ( 'click' , true , false , window, 0 , 0 , 0 , 0 , 0 , false , false , false , false , 0 , null )
}
aLink. dispatchEvent ( event)
} ,
sheetBlob ( sheet, sheetName) {
sheetName = sheetName || 'sheet1'
let workbook = {
SheetNames: [ sheetName] ,
Sheets: { }
}
workbook. Sheets[ sheetName] = sheet
let wopts = {
bookType: 'xlsx' ,
bookSST: false ,
type: 'binary'
}
let wbout = XLSX . write ( workbook, wopts)
let blob = new Blob ( [ s2ab ( wbout) ] , {
type: 'application/octet-stream'
} )
function s2ab ( s) {
if ( typeof ArrayBuffer !== 'undefined' ) {
var buf = new ArrayBuffer ( s. length) ;
var view = new Uint8Array ( buf) ;
for ( var i = 0 ; i != s. length; ++ i) view[ i] = s. charCodeAt ( i) & 0xFF ;
return buf;
} else {
var buf = new Array ( s. length) ;
for ( var i = 0 ; i != s. length; ++ i) buf[ i] = s. charCodeAt ( i) & 0xFF ;
return buf;
}
}
return blob
}
}
Vue. $common = common;
}
}
export default common;
import common from './views/utils/common'
Vue. use ( common) ;
exportExcel: function ( ) {
let aoa = [ [ '姓名' ] ]
for ( let i = 0 ; i < this . dataList. length; i++ ) {
let a = this . dataList[ i]
let itemDevice = [ a. name]
aoa. push ( itemDevice)
}
let cols = [
{ wch: 10 }
]
this . $common. exportExcel ( aoa, '表格.xlsx' , cols)
} ,