这篇文是挺早之前写的了,当时应该是使用的 vue2,后面发现了更简单、更方便、更容易理解的方法,也适用于 vue3,但是只写了导出的方法,后面遇到再补充导入读取,自己也可以看官方,传送门:vue3 使用 xlsx 导出 json 数据为 excel 表格

场景:我们做的后台,老总想要批量导入数据的功能,因此有了导入,后来又想要 excel 表的数据,因此有了导出

一、导入

首先使用以下命令安装 xlsx

npm install xlsx

在需要使用的页面进行引入

import XLSX from "xlsx"

html 写一个选文件的 input,加一个 change 方法

<input type="file" ref="upload_file" accept=".xls,.xlsx" class="upload_file" @change="readExcel($event)" />

js 进行操作,可以把其中的注释取消看看打印的什么方便了解

//data
upload_file: "",
lists: [],

//method
readExcel(e) {
  // 读取表格文件
  let that = this;
  const files = e.target.files;
  if (files.length <= 0) {
    return false;
  } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
    this.$message({
      message: "上传格式不正确,请上传xls或者xlsx格式",
      type: "warning",
    });
    return false;
  } else {
    // 更新获取文件名
    that.upload_file = files[0].name;
  }
  const fileReader = new FileReader();
  fileReader.onload = (ev) => {
    try {
      const data = ev.target.result;
      const workbook = XLSX.read(data, {
        type: "binary",
      });
      const wsname = workbook.SheetNames[0]; //取第一张表
      //console.log(XLSX);
      //console.log(wsname);
      //console.log(workbook);
      const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
      that.lists = [];
      //console.log(ws);
      // 从解析出来的数据中提取相应的数据
      ws.forEach((item) => {
        //读出来的excel表里的数据放在lists数组里
        that.lists.push({
          code: item["编号"],
          name: item["姓名"],
          gender: item["性别"],
          age: item["年龄"],
          card: item["身份证号"],
        });
      });
      // 给后端发请求
      this.submit_form();
    } catch (e) {
      return false;
    }
  };
  fileReader.readAsBinaryString(files[0]);
},


submit_form() {
  //我这里是将lists进行循环遍历,然后分别调接口单个写入数据库创建的
  let that = this;
  let bar = 0, //导入成功数
    foo = 0, //导入失败数
    count = 0; //导入的总数
  this.lists.forEach((e, i) => {
    let url = 接口URL;
    this.$axios.post(url, this.$qs.stringify(e)).then((res) => {
      count++;
      if (res.code == 1) {
        bar++;
      } else {
        foo++;
      }
      if (count == this.lists.length) {
        alert(`共${that.lists.length}条数据,导入成功数:${bar},导入失败数:${foo}`);
        window.location.reload();
      }
    });
  });
},

此时导入的 excel 表内容的格式为
在这里插入图片描述

二、导出

使用命令安装以下依赖

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

创建一个 Export2Excel.js,放在静态资源里需要时引入即可,内容为

/* eslint-disable */
import { saveAs } from 'file-saver'
import XLSX from 'xlsx'

function generateArray(table) {
  var out = [];
  var rows = table.querySelectorAll('tr');
  var ranges = [];
  for (var R = 0; R < rows.length; ++R) {
    var outRow = [];
    var row = rows[R];
    var columns = row.querySelectorAll('td');
    for (var C = 0; C < columns.length; ++C) {
      var cell = columns[C];
      var colspan = cell.getAttribute('colspan');
      var rowspan = cell.getAttribute('rowspan');
      var cellValue = cell.innerText;
      if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;

      //Skip ranges
      ranges.forEach(function (range) {
        if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) {
          for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
        }
      });

      //Handle Row Span
      if (rowspan || colspan) {
        rowspan = rowspan || 1;
        colspan = colspan || 1;
        ranges.push({
          s: {
            r: R,
            c: outRow.length
          },
          e: {
            r: R + rowspan - 1,
            c: outRow.length + colspan - 1
          }
        });
      };

      //Handle Value
      outRow.push(cellValue !== "" ? cellValue : null);

      //Handle Colspan
      if (colspan)
        for (var k = 0; k < colspan - 1; ++k) outRow.push(null);
    }
    out.push(outRow);
  }
  return [out, ranges];
};

function datenum(v, date1904) {
  if (date1904) v += 1462;
  var epoch = Date.parse(v);
  return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}

function sheet_from_array_of_arrays(data, opts) {
  var ws = {};
  var range = {
    s: {
      c: 10000000,
      r: 10000000
    },
    e: {
      c: 0,
      r: 0
    }
  };
  for (var R = 0; R != data.length; ++R) {
    for (var C = 0; C != data[R].length; ++C) {
      if (range.s.r > R) range.s.r = R;
      if (range.s.c > C) range.s.c = C;
      if (range.e.r < R) range.e.r = R;
      if (range.e.c < C) range.e.c = C;
      var cell = {
        v: data[R][C]
      };
      if (cell.v == null) continue;
      var cell_ref = XLSX.utils.encode_cell({
        c: C,
        r: R
      });

      if (typeof cell.v === 'number') cell.t = 'n';
      else if (typeof cell.v === 'boolean') cell.t = 'b';
      else if (cell.v instanceof Date) {
        cell.t = 'n';
        cell.z = XLSX.SSF._table[14];
        cell.v = datenum(cell.v);
      } else cell.t = 's';

      ws[cell_ref] = cell;
    }
  }
  if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
  return ws;
}

function Workbook() {
  if (!(this instanceof Workbook)) return new Workbook();
  this.SheetNames = [];
  this.Sheets = {};
}

function s2ab(s) {
  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;
}

export function export_table_to_excel(id) {
  var theTable = document.getElementById(id);
  var oo = generateArray(theTable);
  var ranges = oo[1];

  /* original data */
  var data = oo[0];
  var ws_name = "SheetJS";

  var wb = new Workbook(),
    ws = sheet_from_array_of_arrays(data);

  /* add ranges to worksheet */
  // ws['!cols'] = ['apple', 'banan'];
  ws['!merges'] = ranges;

  /* add worksheet to workbook */
  wb.SheetNames.push(ws_name);
  wb.Sheets[ws_name] = ws;

  var wbout = XLSX.write(wb, {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary'
  });

  saveAs(new Blob([s2ab(wbout)], {
    type: "application/octet-stream"
  }), "test.xlsx")
}

export function export_json_to_excel({
  multiHeader = [],
  header,
  data,
  filename,
  merges = [],
  autoWidth = true,
  bookType = 'xlsx'
} = {}) {
  /* original data */
  filename = filename || 'excel-list'
  data = [...data]
  data.unshift(header);

  for (let i = multiHeader.length - 1; i > -1; i--) {
    data.unshift(multiHeader[i])
  }

  var ws_name = "SheetJS";
  var wb = new Workbook(),
    ws = sheet_from_array_of_arrays(data);

  if (merges.length > 0) {
    if (!ws['!merges']) ws['!merges'] = [];
    merges.forEach(item => {
      ws['!merges'].push(XLSX.utils.decode_range(item))
    })
  }

  if (autoWidth) {
    /*设置worksheet每列的最大宽度*/
    const colWidth = data.map(row => row.map(val => {
      /*先判断是否为null/undefined*/
      if (val == null) {
        return {
          'wch': 10
        };
      }
      /*再判断是否为中文*/
      else if (val.toString().charCodeAt(0) > 255) {
        return {
          'wch': val.toString().length * 2
        };
      } else {
        return {
          'wch': val.toString().length
        };
      }
    }))
    /*以第一行为初始值*/
    let 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;
  }

  /* add worksheet to workbook */
  wb.SheetNames.push(ws_name);
  wb.Sheets[ws_name] = ws;

  var wbout = XLSX.write(wb, {
    bookType: bookType,
    bookSST: false,
    type: 'binary'
  });
  saveAs(new Blob([s2ab(wbout)], {
    type: "application/octet-stream"
  }), `${filename}.${bookType}`);
}

在需要导出的页面使用,举个例子

downLoad(){
	let arr=[{
	sno:1000,
	username:"司大帅",
	gender:"男",
	age:21,
	card:"412345678987654321"
	},{
	sno:1001,
	username:"司小帅",
	gender:"男",
	age:22,
	card:"41234567898765432X"
	}]
	import("../assets/js/Export2Excel.js").then((excel) => {
	//tHeader 为导出后的表头
	  const tHeader = ["编号", "姓名", "性别", "年龄", "身份证号"];
	  const filterVal = ["sno", "username", "gender", "age", "card"];
	  const list = arr;
	  const data = this.formatJson(filterVal, list);
	  excel.export_json_to_excel({
	    header: tHeader,
	    data,
	    filename:"文件名",
	    autoWidth: true,
	    bookType: "xlsx",
	  });
	});
}
formatJson(filterVal, jsonData) {
  return jsonData.map((v) =>
    filterVal.map((j) => {
      if (j === "timestamp") {
        return parseTime(v[j]);
      } else {
        return v[j];
      }
    })
  );
},

结果
在这里插入图片描述
参考文章:
vue 实现纯前端导入与解析 excel 表格文件
Excel

❀❀❀❀❀❀ 完结散花 ❀❀❀❀❀❀

Written ❤️ sywdebug.
Logo

前往低代码交流专区

更多推荐