JSFiddle - React, Tailwind, and code Playground
by ysuper
HTML
<h1>
前端讀取Excel
</h1>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jexcel/1.5.7/css/jquery.jexcel.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="form-group">
<div class="col-lg-2">
<input type="file" name="xlfile" id="xlf" />
</div>
</div>
</div>
<div id="mytable"></div>
</div>
<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.5/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jexcel/1.5.7/js/jquery.jexcel.js"></script>
</body>
</html>
CSS
body {
padding-top: 1rem;
}
.dataTables_wrapper {
padding-top: 1rem;
}
JavaScript
$("#xlf").change(function() {
"use strict";
var selectedFile = this.files[0];
handleFile(selectedFile);
$("button").show();
});
var fixdata = data => {
"use strict";
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;
};
var handleFile = file => {
"use strict";
var reader = new FileReader();
reader.onload = event => {
var data = event.target.result;
var workbook;
var arr = fixdata(data);
workbook = XLSX.read(btoa(arr), {
type: "base64"
});
var result = {};
workbook.SheetNames.forEach(sheetName => {
var roa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {
header: 1
});
if (roa.length) {
result[sheetName] = roa;
}
});
var dataSet = result[workbook.SheetNames[0]];
console.log(dataSet)
$("#mytable").jexcel({
data: dataSet,
colWidths: [80, 300, 100]
});
};
if (file) {
reader.readAsArrayBuffer(file);
}
};