Home > Web Front-end > JS Tutorial > body text

Vue implements the function of exporting excel tables

亚连
Release: 2018-05-28 11:10:06
Original
3893 people have browsed it

This article mainly introduces the function of Vue to export excel tables. At the end of the article, I mentioned the import and export code of excel tables in Vue. Friends who need it can refer to it

Introduction:

Recently I am using vue to build a backend system. The technology stack is vue iView. After generating a table on the page, iView can export the table, but it can only export in csv format. , 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 }})
     }
     }
    }, '查看订单')
    }
   }
   },
   ...
  ],
Copy after login

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'),
 }
Copy after login

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')
Copy after login

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]))
  }
Copy after login

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
}
Copy after login

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); 
} 
}
Copy after login

2. Export

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

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Detailed explanation of how Vue implements server-side rendering based on Nuxt.js

Express default log component morgan's method

Sample code for React Native floating button component

The above is the detailed content of Vue implements the function of exporting excel tables. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!