在写后台管理系统中。我们往往需要实现做数据的导入导出功能。这次先写导入的功能部分,导出功能暂时先不写。
#### 示例一:是基于vue的前端UI框架iview写的。具体代码如下所示。
~~~
.info-btn {
position: relative;
width: 44px;
height: 24px;
z-index: 1;
.input-page {
position: absolute;
left: 0;
top: 0;
width: 44px;
height: 24px;
border-color: #57c5f7;
outline: none;
background-color: transparent;
filter:alpha(opacity=0);
-moz-opacity:0;
-khtml-opacity: 0;
opacity: 0;
font-size: 8px;
// display: none;
color: #fff;
z-index: 99;
}
.info-font {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
text-align: center;
line-height: 24px;
z-index:2;
}
}
// 隐藏了导入文件的按钮。使用自定义的按钮
导入
~~~
为了容易区别,我把js的代码提取出来
~~~
data: {
rABS: false
}
// 具体方法
importf () {//导入
let that =this;
let file = event.target.files;
if (!file) { return; }
var f = file[0];
{
var reader = new FileReader();
var name = f.name;
reader.onload = function (e) {
var data = e.target.result;
var wb;
if (that.rABS) {
wb = XLSX.read(data, { type: 'binary' });
} else {
var arr = that.fixdata(data);
wb = XLSX.read(btoa(arr), { type: 'base64' });
}
// 打印出excel文件转成普通的json数据
console.log(JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])))
};
if (that.rABS) reader.readAsBinaryString(f);
else reader.readAsArrayBuffer(f);
}
},
fixdata (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;
}
~~~
示例二:纯原生js写的导入功能
[转载于纯原生的js实现excel文件的导入功能](https://www.jianshu.com/p/044c183edf42)
~~~
var rABS = false;
//导入功能
function importf(obj) {
if (!obj.files) { return; }
var f = obj.files[0];
{
var reader = new FileReader();
var name = f.name;
reader.onload = function (e) {
var data = e.target.result;
var wb;
if (rABS) {
wb = XLSX.read(data, { type: 'binary' });
} else {
var arr = fixdata(data);
wb = XLSX.read(btoa(arr), { type: 'base64' });
}
document.getElementById("demo").innerHTML = JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]));
};
if (rABS) reader.readAsBinaryString(f);
else reader.readAsArrayBuffer(f);
}
}
function fixdata(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;
}