导出
1. 步骤一 `npm install --save xlsx file-saver` 安装依赖
2. 需要导出的页面 引入依赖
import XLSX from "xlsx";
import FileSaver from "file-saver";
3. 写入对应事件
// 导出事件
exportExcel() {
// .table捕获excel的表格
let wb = XLSX.utils.table_to_book(document.querySelector(".table"));
let wbout = XLSX.write(wb, {
bookType: "xlsx",
bookSST: true,
type: "array"
});
let name = '想要导出的表格名字'
try {
FileSaver.saveAs(
new Blob([wbout], { type: "application/octet-stream" }),
name + ".xlsx"
);
} catch (e) {
if (typeof console !== "undefined") console.log(e, wbout);
}
return wbout;
}
导入
<template>
<div>
<input type="file" ref="upload" accept=".xls, .xlsx" class="outputlist_upload" />
</div>
</template>
<script>
import XLSX from 'xlsx'export
default { data() { return { outputs: [] }; },
mounted() {
this.$refs.upload.addEventListener("change", e => {
//绑定监听表格导入事件 this.readExcel(e);
});
},
methods: {
readExcel(e) {
//表格导入 var that = this;
const files = e.target.files; console.log(files);
if (files.length <= 0) {
//如果没有文件名
return false;
} else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
this.$Message.error("上传格式不正确,请上传xls或者xlsx格式");
return false; } 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];
//取第一张表
const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);
//生成json表格内容 console.log(ws,111111111);
that.outputs = [];
//清空接收数据
//编辑数据
for (var i = 0; i < ws.length; i++) {
var sheetData = { address: ws[i].addr, value: ws[i].value };
that.outputs.push(sheetData);
}
this.$refs.upload.value = "";
} catch (e) { return false; }
};
fileReader.readAsBinaryString(files[0]); } }};
</script>
<style lang="stylus" scoped></style>
网友评论