Home  >  Article  >  Web Front-end  >  vue + iView export excel table

vue + iView export excel table

php中世界最好的语言
php中世界最好的语言Original
2018-06-12 14:07:578608browse

This time I will bring you vue iView to export excel table. What are the precautions for vue iView to export excel table? Here is a practical case, let’s take a look.

Introduction:

Recently using vue to build a backend system, the technology stack vue iView, after generating a table in the page, iView can be implemented Tables can only be exported in csv format, which is not suitable for project needs.

If you want to export Excel

  • Create a file (vendor) in the src directory and enter Blob.js and Export2Excel.js

  • npm install -S file-saver A web application used to generate files

  • npm install -S xlsx A parser for spreadsheet format

  • npm install -D script-loader Hang js globally

Table structure

The table structure in the rendered page is The columns rendered by columns and tableData rows are table header data and tableData is table entity content.

columns1: [
   {
   title: '序号',
   key: 'serNum'
   },
   {
   title: '选择',
   key: 'choose',
   align: 'center',
   render: (h, params) => {
    if (params.row.status !== '1' && params.row.status !== '2') {
    return h('p', [
     h('checkbox', {
     props: {
      type: 'selection'
     },
     on: {
      'input': (val) => {
      console.log(val)
      }
     }
     })
    ])
    } else {
    return h('span', {
     style: {
     color: '#587dde',
     cursor: 'pointer'
     },
     on: {
     click: () => {
      // this.$router.push({name: '', query: { id: params.row.id }})
     }
     }
    }, '查看订单')
    }
   }
   },
   ...
  ],

tableData will not be written here. For the specific data structure, see iViewAPI

in the build directory webpack. base.conf.js configures the path we want to load

alias: {
  'src': path.resolve(__dirname, '../src'),
 }

Introduce dependencies into the current page

require('script-loader!file-saver')
 // 转二进制用
 require('script-loader!src/vendor/Blob')
 // xlsx核心
 require('script-loader!xlsx/dist/xlsx.core.min')

When we want to export the table, execute the @click event and call the handleDownload function

handleDownload() {
  this.downloadLoading = true
  require.ensure([], () => {
   const {export_json_to_excel} = require('src/vendor/Export2Excel')
   const tHeader = Util.cutValue(this.columns1, 'title')
   const filterVal = Util.cutValue(this.columns1, 'key')
   const list = this.tableData1
   const data = this.formatJson(filterVal, list)
   export_json_to_excel(tHeader, data, '列表excel')
   this.downloadLoading = false
  })
  },
  formatJson(filterVal, jsonData) {
  return jsonData.map(v => filterVal.map(j => v[j]))
  }

Util.cutValue is a public method, the purpose is to convert the values ​​​​of tHeader and filterVal into arrays to generate tables

### Util module
// 截取value值
utils.cutValue = function (target, name) {
 let arr = []
 for (let i = 0; i < target.length; i++) {
 arr.push(target[i][name])
 }
 return arr
}

Export2Excel.js/Blob.js code

Let’s look at the import and export of excel tables in vue

Note: To implement the import and export of tables in vue, you must first install two dependencies,

npm install -S file-saver xlsx and npm install -D script-loader. Secondly, create a new folder vendor (the name is arbitrary) in the project src directory, and place two files Blob.js and Export2Excal.js under this folder (download address: http://files.cnblogs.com/files/wangyunhui /vendor.rar). After that, you can happily import and export smiles.

1. Import

1.<input id="upload" type="file" @change="importfxx(this)" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" /> 
importfxx(obj) { 
let _this = this; 
console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxx1"); 
let inputDOM = this.$refs.inputer; 
// 通过DOM取文件数据 
this.file = event.currentTarget.files[0]; 
var rABS = false; //是否将文件读取为二进制字符串 
var f = this.file; 
var reader = new FileReader(); 
//if (!FileReader.prototype.readAsBinaryString) { 
FileReader.prototype.readAsBinaryString = function(f) { 
var binary = ""; 
var rABS = false; //是否将文件读取为二进制字符串 
var pt = this; 
var wb; //读取完成的数据 
var outdata; 
var reader = new FileReader(); 
reader.onload = function(e) { 
var bytes = new Uint8Array(reader.result); 
var length = bytes.byteLength; 
for(var i = 0; i < length; i++) { 
binary += String.fromCharCode(bytes[i]); 
} 
var XLSX = require(&#39;xlsx&#39;); 
if(rABS) { 
wb = XLSX.read(btoa(fixdata(binary)), { //手动转化 
type: &#39;base64&#39; 
}); 
} else { 
wb = XLSX.read(binary, { 
type: &#39;binary&#39; 
}); 
} 
outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);//outdata就是你想要的东西 
} 
reader.readAsArrayBuffer(f); 
} 
if(rABS) { 
reader.readAsArrayBuffer(f); 
} else { 
reader.readAsBinaryString(f); 
} 
}

2. Export

inportexcel: function() { //兼容ie10哦! 
require.ensure([], () => {         
const { export_json_to_excel } = require('../../vendor/Export2Excel');  //引入文件       
const tHeader = ['用户名', '姓名', '部门', '职位', '邮箱', '充值']; //将对应的属性名转换成中文 
// const tHeader = []; 
         
const filterVal = ['userName', 'realName', 'department', 'position', 'email', 'money'];//table表格中对应的属性名          
const list = this.sels;         
const data = this.formatJson(filterVal, list);         
export_json_to_excel(tHeader, data, '列表excel');       
}) 
}

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to php Chinese Other related articles online!

Recommended reading:

The use of Postman token parameters

How to use angular4 shared component communication

The above is the detailed content of vue + iView export excel table. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn