1. Official address github.com/SheetJS/js-…

2. Download xlsx.core.min.js from dist

3. Read Excel

// Read the local Excel file
function readWorkbookFromLocalFile(file, callback) {
    var reader = new FileReader();
    reader.onload = function(e) {
            var data = e.target.result;
            var workbook = XLSX.read(data, {type: 'binary'});
            if(callback) callback(workbook);
    };
    reader.readAsBinaryString(file);
}

Copy the code
// To read an Excel file from the network, the URL must be in the same domain, otherwise an error is reported
function readWorkbookFromRemoteFile(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function(e) {
        if(xhr.status == 200) {
            var data = new Uint8Array(xhr.response)
            var workbook = XLSX.read(data, {type: 'array'});
            if(callback) callback(workbook); }}; xhr.send(); }Copy the code

4. Read workbook

/ / read the workbook
function readWorkbook(workbook) {
  let sheetNames = workbook.SheetNames; // A collection of worksheet names
  let worksheet = workbook.Sheets[sheetNames[0]].// Here we only read the first sheet
  let csv = XLSX.utils.sheet_to_csv(worksheet);
  return csv2table(csv)
}
// Converting CSV to a simple table ignores cell merging and appends excel like indexes to the first row and column
function csv2table(csv) {
  let arrs = [];
  let rows = csv.split('\n');
  let first_rows = rows.shift().split(', '); // The first line is useless
  rows.pop(); // The last line is useless
  rows.forEach(function (row, idx) {
    let columns = row.split(', ');
    let obj = {}
    columns.forEach(function (col, idx) {
      obj[first_rows[idx]] = col
    })
    arrs.push(obj)
  });
  return arrs;
}
Copy the code