Introduction of package
npm install xlsx -S // Release time is 0.16.9
Copy the code
The new excel. Js
Create a libs folder under SRC and create an excel. Js folder
import XLSX from 'xlsx' function autoWidthFunc (ws, data) { // set worksheet max width per col const colWidth = data.map(row => row.map(val => { var reg = new RegExp("[\\u4E00-\\u9FFF]+","g"); If (val == null) {return {WCH: 10}} else if (reg.test(val)) {return {WCH: val.toString().length * 2 } } else { return { wch: val.toString().length } } })) // start in the first row const result = colWidth[0] for (let i = 1; i < colWidth.length; i++) { for (let j = 0; j < colWidth[i].length; j++) { if (result[j].wch < colWidth[i][j].wch) { result[j].wch = colWidth[i][j].wch } } } ws['! cols'] = result } function jsonToArray (key, jsonData) { return jsonData.map(v => key.map(j => { return v[j] })) } const exportArrayToExcel = ({ key, data, title, filename, autoWidth }) => { const wb = XLSX.utils.book_new() const arr = jsonToArray(key, data) arr.unshift(title) const ws = XLSX.utils.aoa_to_sheet(arr) if (autoWidth) { autoWidthFunc(ws, arr) } XLSX.utils.book_append_sheet(wb, ws, filename) XLSX.writeFile(wb, filename + '.xlsx') } export default { exportArrayToExcel }Copy the code
Vue page
import excel from '@/libs/excel' export default { data () { return { dataList: [{/ / dataList fields in the title, key needs corresponding 'app_id' : '1', 'app_source' : 'taobao', 'cars' :' 666666 '}, {' app_id ': '2', 'app_source' : 'jingdong', 'cars' :' 666667 '}}}], the methods: ExportExcel () {const params = {title: [' order number ', 'order source ',' license number '], key: ['app_id', 'app_source', 'cars'], data: this.datalist, // autoWidth: Filename: 'list'} excel. ExportArrayToExcel (params)}Copy the code
Results show
Reference documentation
Vue2 export excel
XLSX NPM package address
conclusion
Through the above simple steps can achieve pure front-end export Excel. Have the need to small partners can see the horse first