Although we can’t read Excel files on Web API directly, we can use the xlsx
package to finish the task.
Version
Brave 1.45.127
xlsx
Excel file is read by Web API.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
lang="javascript"
src="https://cdn.sheetjs.com/xlsx-latest/package/dist/xlsx.full.min.js"></script>
<title>HTML Lab</title>
</head>
<body>
<input
id="uploadFile"
type="file"
onchange="onChange()"
accept=".csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
</body>
<script>
let { read, utils } = XLSX
let onChange = () => {
let file = document.querySelector('#uploadFile').files[0]
let fileReader = new FileReader()
fileReader.readAsArrayBuffer(file)
fileReader.onload = e => {
let workbook = read(e.target.result)
let sheetName = workbook.SheetNames[0]
let sheet = workbook.Sheets[sheetName]
let data = utils.sheet_to_json(sheet)[0]
console.log(data)
}
}
</script>
</html>
Line 6
<script
lang="javascript"
src="https://cdn.sheetjs.com/xlsx-latest/package/dist/xlsx.full.min.js"></script>
- Load XLSX package by CDN
Line 12
<input
id="uploadFile"
type="file"
onchange="onChange()"
accept=".csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
id
:defineid
for DOM elementonchange
:fireonChange()
onchange
eventaccpet
:only Excel files accept
Line 19
let { read, utils } = XLSX
- Extract
read()
andutils()
fromXLSX
Line 21
let onChange = () => {
let file = document.querySelector('#uploadFile').files[0]
let fileReader = new FileReader()
fileReader.readAsArrayBuffer(file)
}
file
:get selected file byid
andquerySelector()
fileReader
:createFileReader
instancereadAsArrayBuffer()
:usereadAsArrayBuffer()
to fillfileReader
fromfile
Object
Line 26
fileReader.onload = e => {
let workbook = read(e.target.result)
let sheetName = workbook.SheetNames[0]
let sheet = workbook.Sheets[sheetName]
let data = utils.sheet_to_json(sheet)[0]
console.log(data)
}
onload()
:read Excel file whenfileReader
Object finishes loadingread()
:read selected file frome.target.result
, which is an ArrayBufferSheetName[]
:get the name of the sheetsSheets
:useSheets[]
by thesheetName
to get the sheetutils.sheet_to_json()
:convert sheet to JSON
Conclusion
- Reading Excel on Web API is much the sam as Reading Excel on Apline. Only difference is that we have to use
id
andquerySelector()
to get selected files