This is the 6th day of my participation in the August More Text Challenge

Exporting table data

Sometimes when doing background projects usually have such a requirement, need to export a lot of user filtering out of the data for transmission, in fact, can use the original JS implementation, today just record the use of plug-in implementation method, after all, plug-in compatible good open speed will be a little faster. Two plug-ins are used: file-Saver XLSX

  • File-saver is responsible for saving files
  • XLSX is responsible for converting data to tables

The specific use

The installation

npm install -S file-saver xlsx npm install -D script-loader

Script-loader is mainly for use if the XLSX and file-saver cannot be loaded. It seems that only import is needed now.

Encapsulate export code

import fs from 'file-saver' import XLSX from 'xlsx' export default (json, fields, ForEach (item => {for (let I in item) {if (fields.hasownProperty (I)) { item[fields[i]] = item[i]; } delete item[i]; // delete the original object attributes}}) let sheetName = filename //excel filename let wb = xlsx.utils.book_new () And a table object that maps table names to table objects. The xlsx.utils.book_new utility creates a new workbook object. Let ws = xlsx.utils.json_to_sheet (json, {header: object.values (fields)}) // Convert an array of JS objects to a worksheet. wb.SheetNames.push(sheetName) wb.Sheets[sheetName] = ws const defaultCellStyle = { font: { name: "Verdana", sz: 13, color: "FF00FF88" }, fill: { fgColor: { rgb: "FFFFAA00" } } }; Let wopts = {bookType: 'XLSX ', bookSST: false, type: 'binary', cellStyles: true, defaultCellStyle: defaultCellStyle, showGridLines: Let wbout = xlsx. write(wb, wopts) let blob = new blob ([s2ab(wbout)], {type: 'application/octet-stream' }) fs.saveAs(blob, filename + '.xlsx') } const s2ab = s => { if (typeof ArrayBuffer ! == 'undefined') { var buf = new ArrayBuffer(s.length) var view = new Uint8Array(buf) for (var i = 0; i ! = s.length; ++i) view[i] = s.charCodeAt(i) & 0xff return buf } else { var buf = new Array(s.length); for (var i = 0; i ! = s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF; return buf; }}Copy the code

Specific page usage

Before using the first introduction of their own written package file, and then the corresponding place can be called. import Export from “.. /.. /utils/export”;

ExportToExcel () {let fields = {date: "date ", name:" name ", type: "province ", area:" address ", code: "zip ", test: "Test"}; // let data = JSON.parse(JSON.stringify(this.tableData3)); Export(this.tableData3, fields, "test "); }Copy the code