[TOC]
定义filePicked函数,file是上传的xlsx文件,callback回调。
~~~
function filePicked(file, callback) {
// Get The File From The Input
// var oFile = dom.target.files[0];
var oFile = file;
var sFilename = oFile.name;
// Create A File Reader HTML5
var reader = new FileReader();
// Ready The Event For When A File Gets Selected
reader.onload = function(e) {
var data = e.target.result;
var cfb = XLSX.read(data, {type: 'binary'});
// console.log(cfb)
cfb.SheetNames.forEach(function(sheetName) {
// Obtain The Current Row As CSV
var sCSV = XLS.utils.make_csv(cfb.Sheets[sheetName]);
var oJS = XLS.utils.sheet_to_json(cfb.Sheets[sheetName]);
// $("#my_file_output").html(sCSV);
callback(oJS)
// return oJS
});
};
// Tell JS To Start Reading The File.. You could delay this if desired
reader.readAsBinaryString(oFile);
// return reader
}
~~~
使用示例:
~~~
html:
<input type="file" id="my_file_input" />
js:
$("#my_file_input").change(function(){
filePicked($(this)[0].files[0], function(data){
var s = {
results:data,
count:data.length,
}
console.log(s)
})
})
~~~
项目地址:[js-xlsx](https://github.com/SheetJS/js-xlsx)