<script src="./js/xlsx.core.min.js"></script>
<input type="file" id="excel" style="display: none;" />
<a href="#" οnclick="$('#excel').click()"">xxx</a>
var a = []
if (typeof (FileReader.prototype.readAsBinaryString) !== "function") {
FileReader.prototype.readAsBinaryString = function (fileData) {
let binary = "";
let pt = this;
let reader = new FileReader();
reader.onload = function (e) {
let bytes = new Uint8Array(reader.result);
let length = bytes.byteLength;
for (let i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
let obj = {};
obj.target = { result: binary };
pt.onload(obj);
}
reader.readAsArrayBuffer(fileData);
}
}
document.querySelector('#excel').onchange = function (e) {
let file = e.target.files[0];
readWorkbookFromLocalFile(file, function (workbook) {
readWorkbook(workbook);
});
}
// 读取本地excel文件,读取Excel文件对象
function readWorkbookFromLocalFile(file, callback) {
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
var workbook = XLSX.read(data, { type: 'binary' });
console.log(workbook);
if (callback) callback(workbook);
};
reader.readAsBinaryString(file);
}
// 转成cvs 要注意Execel表格内容不能包含英文的,不然解析出来的数据格式会有问题
function readWorkbook(workbook) {
var sheetNames = workbook.SheetNames; // 工作表名称集合
var worksheet = workbook.Sheets[sheetNames[0]]; // 这里我们只读取第一张sheet
var csv = XLSX.utils.sheet_to_csv(worksheet);
console.log(csv);
var rows = csv.split('\n'); // 转化为数组
rows.pop(); // 最后一行没用的
console.log(rows); // 打印输出的数组
rows.forEach(function (val, key, item) {
console.log("val", val);
console.log("key", key);
console.log("item", item);
a.push(val.split(','))
});
console.log("a", a[1][2]);
}