JS 读取本地Excel文件

时间:2023-02-08 10:29:46

  首先我们先引用一个Excel的类库xlsx.full.min.js

中间处理:

'use strict';
var ExcelReader = {
isFirstRead: true,
fixdata: function (data) {
var o = "",
l = 0,
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;
},
read: function (file, callback, sheetIndex) {
var self = this;
var isABS = false;
if (this.isFirstRead) {
this.extendFileReader();
}
if (!file) {
return;
}
if (!sheetIndex) {
sheetIndex = 0;
}
var f;
if (file.rawFile) {
f = file.rawFile;//使用Kendo Ui的上传控件
}
else {
f = file;
}
var reader = new FileReader();
reader.onload = function (e) {
var data;
var wb;
if (!isABS) {
data = e.target.result;
}
else {
data = e;
}
if (!isABS && !data.slice) {
isABS = true;
reader.readAsBinaryString(f);
return;
}
if (!isABS) {
wb = XLSX.read(btoa(self.fixdata(data)), {
type: 'base64'
});
}
else {
wb = XLSX.read(btoa(data), {
type: 'base64'
});
}
callback(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[sheetIndex]]));
};
reader.readAsArrayBuffer(f);
},
extendFileReader: function () {
this.isFirstRead = false;
if (!FileReader.prototype.readAsBinaryString) {
FileReader.prototype.readAsBinaryString = function (fileData) {
var binary = "";
var self = this;
var reader = new FileReader();
reader.onload = function (e) {
var bytes = new Uint8Array(reader.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
self.onload(binary);
}
reader.readAsArrayBuffer(fileData);
}
}
}
}

  

使用方式:

$("#ImportCtrl").kendoUpload({
select: function (e) {
$.each(e.files, function (index, value) {
ExcelReader.read(value, importFilesSuccess);
});
}
}).data("kendoUpload"); var importFilesSuccess = function (d) {
//d:JSON DATA
}