方法一:vue
1、安裝依賴(前面基本同樣)webpack
npm install file-saver --save
npm install xlsx --save
npm install script-loader --save-dev
2、下載兩個所須要的js文件Blob.js和 Export2Excel.jsweb
這裏貼下下載地址:npm
http://xiazai.jb51.net/201708/yuanma/Export2Exce_jb51.rar
3、src目錄下新建vendor文件夾,將Blob.js和 Export2Excel.js放進去。json
4、更改webpack.base.conf.js配置app
在resolve的alias:
'vendor': path.resolve(__dirname, '../src/vendor')
5、在.vue文件中
script部分ui
data(){ return{ myTable:[ { no: 1, goodsName:'哇哈哈', number:2, price:16, customerName:'柳生', phone:18976545678, }, { no:2, goodName:'棒棒糖', number:5, price:10, customerName:‘張三’, phone:18166754345, }, ] } methods:{ formatJson(filterVal, jsonData) { return jsonData.map(v => filterVal.map(j => v[j])) }, export2Excel() { require.ensure([], () => { const { export_json_to_excel } = require('../../../vendor/Export2Excel'); const tHeader = ['序號', '商品名稱', '數量', '單價', '會員姓名', '手機號碼'];
const filterVal = ['no', 'goodsName', 'number', 'price', 'customerName', 'phone']
const list = this.myTable; const data = this.formatJson(filterVal, list); export_json_to_excel(tHeader, data, '商品管理列表'); }) } }
方法二:this
import XLSX from 'xlsx'
data() {
return {
list: [
},
methods: { aaa() { var arr = this.list let mergesArr = [] arr[0].forEach((item, index) => { if (item) { mergesArr[mergesArr.length] = { s: {}, e: {} } mergesArr[mergesArr.length - 1].s.c = index mergesArr[mergesArr.length - 1].s.r = 0 mergesArr[mergesArr.length - 1].e.c = index mergesArr[mergesArr.length - 1].e.r = 0 } else { mergesArr[mergesArr.length - 1].e.c = index } }) mergesArr.forEach((item, index) => { if (arr[1][item.e.c] === '') { mergesArr[index].e.r = 1 } }) return mergesArr }, printPages(wscols, xlsxName) {
const ws = XLSX.utils.aoa_to_sheet(this.list) ws['!cols'] = [{ wch: 5 }, { wch: 20 }, { wch: 20 }, { wch: 20 }, { wch: 20 }, { wch: 10 }] ws['!merges'] = this.aaa() const wb = XLSX.utils.book_new() XLSX.utils.book_append_sheet(wb, ws, '商品管理列表') /* generate file and send to client */ XLSX.writeFile(wb, '商品管理列表' + '.xlsx') }}