使用jquery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Excel批量处理</title>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/xlsx/0.11.5/xlsx.core.min.js"></script>
</head>
<body>
<input type="file" id="excel-file">
<textarea id="area"></textarea>
<script>
//给input标签绑定change事件,一上传选中的.xls文件就会触发该函数
$('#excel-file').change(function (e) {
var files = e.target.files;
var fileReader = new FileReader();
fileReader.onload = function (ev) {
try {
var data = ev.target.result
var workbook = XLSX.read(data, {
type: 'binary'
}) // 以二进制流方式读取得到整份excel表格对象
var persons = []; // 存储获取到的数据
} catch (e) {
console.log('文件类型不正确');
return;
}
// 表格的表格范围,可用于判断表头是否数量是否正确
var fromTo = '';
// 遍历每张表读取
for (var sheet in workbook.Sheets) {
if (workbook.Sheets.hasOwnProperty(sheet)) {
fromTo = workbook.Sheets[sheet]['!ref'];
console.log(fromTo);
persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
//break; // 如果只取第一张表,就取消注释这行
}
}
//在控制台打印出来表格中的数据
console.log(persons);
$("#area").val(JSON.stringify(persons));
};
// 以二进制方式打开文件
fileReader.readAsBinaryString(files[0]);
});
</script>
</body>
</html>
vue结合elementui表格
导入数据后
1 页面使用
<el-upload
class="upload-demo"
action=""
:on-change="handleChange"
:show-file-list="false"
:auto-upload="false"
>
<el-button type="primary">读取excel文件</el-button>
</el-upload>
data数据中定义
tableData:[{}]
fileContent: "",
file: "",
data: "",
//批量导入数据
// 核心部分代码(handleChange 和 importfile)
handleChange(file) {
console.log(file);
this.fileContent = file.raw;
const fileName = file.name;
const fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
if (this.fileContent) {
if (fileType === "xlsx" || fileType === "xls") {
this.importfile(this.fileContent);
} else {
this.$message({
type: "warning",
message: "附件格式错误,请重新上传!",
});
}
} else {
this.$message({
type: "warning",
message: "请上传附件!",
});
}
},
importfile(obj) {
console.log(obj);
const reader = new FileReader();
const _this = this;
reader.readAsArrayBuffer(obj);
reader.onload = function () {
const buffer = reader.result;
const bytes = new Uint8Array(buffer);
const length = bytes.byteLength;
let binary = "";
for (let i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
const XLSX = require("xlsx");
const wb = XLSX.read(binary, {
type: "binary",
});
const outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
this.data = [...outdata];
const arr = [];
this.data.map((v) => {
const obj = {};
obj.name = String(v["日期"]);
obj.id = String(v["姓名"]);
obj.number = String(v["地址"]);
obj.edit = false;
console.log(obj);
arr.push(obj);
});
_this.tableData = _this.tableData.concat(arr);
console.log(_this.tableData);
};
},