Skip to content

Instantly share code, notes, and snippets.

@silencesys silencesys/index.html

Last active Dec 15, 2019
Embed
What would you like to do?
Read XLSX file in JavaScript.

Read .XLSX file in JavaScript

This gist contains basic code to read .xlsx from the server with XMLHttpRequest method and then storing it in variable to allow searching in stored data.

For XLSX file parsing I'm using SheetJs/sheetjs library.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JavaScript Reads Excel</title>
<style>
body {
background-color: darkslategrey;
color: whitesmoke;
}
</style>
<!-- necessary javascript libraries -->
<script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
</head>
<body>
<div id="jrex--results">
<input type="text" id="jrex--input">
<p id="jrex--output">Type into input and hit enter to find something.</p>
</div>
<script>
const jrexInput = document.getElementById('jrex--input')
jrexInput.addEventListener('change', jrexInputChanged)
const jrexOutput = document.getElementById('jrex--output')
// Set custom key if the file is structured to array of objects
let jrexKeyName = 'id'
// This variable will contain xlsx data
let jrexXlsData = []
// Change url
jrexInitialize('http://laboratory.localhost/javascript-reads-excel/bosworth.xlsx')
/**
* Initialize JREX and load XLS file from the specified URL.
*
* @param {String} url
* @return void
*/
function jrexInitialize(url) {
const jrexRequestXlsFile = new XMLHttpRequest()
jrexRequestXlsFile.open('GET', url, true)
jrexRequestXlsFile.responseType = 'arraybuffer'
jrexRequestXlsFile.onload = function (e) {
const jrexRequestData = new Uint8Array(jrexRequestXlsFile.response)
const jrexWorkbook = XLSX.read(jrexRequestData, { type: 'array' })
jrexWorkbook.SheetNames.forEach(function (sheetName) {
jrexXlsData = XLSX.utils.sheet_to_row_object_array(jrexWorkbook.Sheets[sheetName])
})
}
jrexRequestXlsFile.send()
}
/**
* Handle jrex input change.
*
* @param {DomEvent} e
* @return void
*/
function jrexInputChanged(e) {
const jrexInputValue = e.target.value
let jrexFinds = jrexXlsData.find(item => item[jrexKeyName].toString() === jrexInputValue)
if (jrexFinds !== undefined) {
jrexOutput.innerText = JSON.stringify(jrexFinds)
// Logic
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.