Home Web Front-end JS Tutorial How to export excel table with Vue

How to export excel table with Vue

May 26, 2018 am 10:41 AM
excel Export sheet

This time I will show you how to use Vue to export excel tables. What are the precautions for exporting excel tables with Vue. The following 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 The table can be exported, but it can only be exported in csv format, which is not suitable for project requirements.

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('xlsx'); 
if(rABS) { 
wb = XLSX.read(btoa(fixdata(binary)), { //手动转化 
type: 'base64' 
}); 
} else { 
wb = XLSX.read(binary, { 
type: 'binary' 
}); 
} 
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('../../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');       
}) 
}
Copy after login

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

How to make js convert the key value string into a json string

How to convert webpack4.0 Packaging optimization

The above is the detailed content of How to export excel table with Vue. For more information, please follow other related articles on the PHP Chinese website!

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

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Steps to adjust the format of pictures inserted in PPT tables Steps to adjust the format of pictures inserted in PPT tables Mar 26, 2024 pm 04:16 PM

Steps to adjust the format of pictures inserted in PPT tables

How to filter more than 3 keywords at the same time in excel How to filter more than 3 keywords at the same time in excel Mar 21, 2024 pm 03:16 PM

How to filter more than 3 keywords at the same time in excel

What should I do if the frame line disappears when printing in Excel? What should I do if the frame line disappears when printing in Excel? Mar 21, 2024 am 09:50 AM

What should I do if the frame line disappears when printing in Excel?

How to change excel table compatibility mode to normal mode How to change excel table compatibility mode to normal mode Mar 20, 2024 pm 08:01 PM

How to change excel table compatibility mode to normal mode

How to make a table for sales forecast How to make a table for sales forecast Mar 20, 2024 pm 03:06 PM

How to make a table for sales forecast

How to set superscript in excel How to set superscript in excel Mar 20, 2024 pm 04:30 PM

How to set superscript in excel

Where to set excel reading mode Where to set excel reading mode Mar 21, 2024 am 08:40 AM

Where to set excel reading mode

How to use the iif function in excel How to use the iif function in excel Mar 20, 2024 pm 06:10 PM

How to use the iif function in excel

See all articles