HTML片段:
<div>
<input type="file" οnchange="importf(this)" />
<div id="demo"></div>
</div>
js片段:
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.6.0.min.js" defer></script>
<script src="https://cdn.bootcss.com/xlsx/0.12.9/xlsx.full.min.js" defer></script>
<script defer>
let transferData;//读取完成的数据
let rABS = false;
//是否将文件读取为二进制字符串
function importf(obj) {//导入
if(!obj.files) { return; }
var f = obj.files[0];
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
if(rABS) {
transferData = XLSX.read(btoa(fixdata(data)), {//手动转化
type: 'base64'
});
} else {
transferData = XLSX.read(data, {
type: 'binary'
});
}
var seltext=transferData.SheetNames[0]//是获取Sheets中第一个Sheet的名字
//transferData.Sheets[Sheet名]获取第一个Sheet的数据
// document.getElementById("demo").innerHTML= JSON.stringify( XLSX.utils.sheet_to_json(transferData.Sheets[transferData.SheetNames[0]]) );
var objData = JSON.stringify( XLSX.utils.sheet_to_json(transferData.Sheets[seltext]) );
console.log(objData);
let obj = JSON.parse(objData)
console.log('转换后',obj)
}
if(rABS) {
reader.readAsArrayBuffer(f);
} else {
reader.readAsBinaryString(f);
}
function fixdata(data) {
//文件流转BinaryString
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;
}
}
</script>