You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
111 lines
3.2 KiB
111 lines
3.2 KiB
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>test</title>
|
|
</head>
|
|
<body>
|
|
<input type="file" id="open-excel" >
|
|
<div class="open"></div>
|
|
</body>
|
|
</html>
|
|
|
|
<script src="../static/assets/js/JQuery.js"></script>
|
|
<script src="https://cdn.bootcss.com/xlsx/0.11.9/xlsx.core.min.js"></script>
|
|
<script type="text/javascript">
|
|
$(function(){
|
|
$('#open-excel').change(function(e) {
|
|
var files = e.target.files;
|
|
var fileReader = new FileReader();
|
|
fileReader.readAsBinaryString(files[0]); // 以二进制方式打开文件
|
|
fileReader.onload = function(ev) {
|
|
try {
|
|
var data = ev.target.result,
|
|
workbook = XLSX.read(data, {
|
|
type: 'binary'
|
|
}),
|
|
values = []; // 存储获取到的数据
|
|
} catch (e) {
|
|
console.log('文件类型不正确');
|
|
return;
|
|
}
|
|
|
|
// 遍历每张表读取
|
|
for (var sheet in workbook.Sheets) {
|
|
if (workbook.Sheets.hasOwnProperty(sheet)) {
|
|
// 得到表数据并转成json格式
|
|
values = values.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
|
|
var html = json2Html(values); // 把获取到的数据添加表格
|
|
console.log('html',html)
|
|
$('.open').html(html)
|
|
break; // 如果只取第一张表,加上这行
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
|
|
|
|
htmlKit = {
|
|
_tags: [], html: [],
|
|
_createAttrs: function (attrs) {
|
|
var attrStr = [];
|
|
for (var key in attrs) {
|
|
if (!attrs.hasOwnProperty(key)) continue;
|
|
attrStr.push(key + "=" + attrs[key] + "")
|
|
}
|
|
return attrStr.join(" ")
|
|
},
|
|
_createTag: function (tag, attrs, isStart) {
|
|
if (isStart) {
|
|
return "<" + tag + " " + this._createAttrs(attrs) + ">"
|
|
} else {
|
|
return "</" + tag + ">"
|
|
}
|
|
},
|
|
start: function (tag, attrs) {
|
|
this._tags.push(tag);
|
|
this.html.push(this._createTag(tag, attrs, true))
|
|
},
|
|
end: function () {
|
|
this.html.push(this._createTag(this._tags.pop(), null, false))
|
|
},
|
|
tag: function (tag, attr, text) {
|
|
this.html.push(this._createTag(tag, attr, true) + text + this._createTag(tag, null, false))
|
|
},
|
|
create: function () {
|
|
return this.html.join("")
|
|
}
|
|
};
|
|
|
|
function json2Html(data) {
|
|
console.log('data',data)
|
|
var hk = htmlKit;
|
|
hk.start("table", {"cellpadding": "10","cellspacing":"0", "border": "1"});
|
|
hk.start("thead");
|
|
hk.start("tr");
|
|
hk.end();
|
|
hk.end();
|
|
hk.start("tbody");
|
|
$.each(data,function (k, v) {
|
|
if(k==0){
|
|
hk.start("tr");
|
|
$.each(v, function(key, val) {
|
|
hk.tag("td", null, key)
|
|
});
|
|
hk.end()
|
|
}
|
|
hk.start("tr");
|
|
$.each(v, function(key, val) {
|
|
hk.tag("td", null, val)
|
|
});
|
|
hk.end()
|
|
});
|
|
hk.end();
|
|
hk.end();
|
|
return hk.create()
|
|
}
|
|
|
|
})
|
|
|
|
</script>
|