純前端 vue+ js-xlsx 導入excel表格


<template>
<div class="index">
<input type="file" @change="importFile(this)" id="imFile" style="display: none"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
<Button type="primary" @click="uploadFile">導入</Button>
</div>
</template>

<script>
// 引入xlsx
var XLSX = require("xlsx");
export default {
name: "Index",
data() {
return {
fullscreenLoading: false, // 加載中
imFile: "", // 導入文件el
errorMsg: "", // 錯誤信息內容
};
},
mounted() {
this.imFile = document.getElementById("imFile");
},
methods: {
uploadFile: function() {
// 點擊導入按鈕
this.imFile.click();
},

importFile: function() {
// 導入excel
this.fullscreenLoading = true;
let obj = this.imFile;
if (!obj.files) {
this.fullscreenLoading = false;
return;
}
var f = obj.files[0];
var reader = new FileReader();
let $t = this;
reader.onload = function(e) {
var data = e.target.result;
if ($t.rABS) {
$t.wb = XLSX.read(btoa(this.fixdata(data)), {
// 手動轉化
type: "base64"
});
} else {
$t.wb = XLSX.read(data, {
type: "binary"
});
}
let json = XLSX.utils.sheet_to_json($t.wb.Sheets[$t.wb.SheetNames[0]]);
$t.dealFile(json); // analyzeData: 解析導入數據
};
if (this.rABS) {
reader.readAsArrayBuffer(f);
} else {
reader.readAsBinaryString(f);
}
},
dealFile: function(data) {
// 處理導入的數據
console.log(data);
this.imFile.value = "";
this.fullscreenLoading = false;
if (data.length <= 0) {
this.errorMsg = "請導入正確信息";
} else {
//導入成功,處理數據
this.$http.post("collector/import", data).then(
function(response) {
if (response.body.status == 1) {

} else {
if (response.body.status == "10101") {
this.$Message.info("未登錄");
this.$router.push("/");
}
this.$Message.info(response.body.message);
}
},
function() {}
);
}
},

fixdata: function(data) {
// 文件流轉BinaryString
var o = "";
var l = 0;
var w = 10240;
for (; l < data.byteLength / w; ++l) {
o += String.fromCharCode.apply(
null,
new Uint8Array(data.slice(l * w, l * w + w))
);
}
o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
return o;
}
}
};
</script>



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM