Reading Excel files (XLSX) is a common task that developers may encounter while working with data-driven applications. In this blog post, we will explore how to read XLSX files in JavaScript using a popular library called SheetJS.
Prerequisites
- Basic knowledge of JavaScript
- A modern web browser
Step 1: Installing SheetJS
SheetJS is an open-source library that can parse and write various spreadsheet formats, including XLSX, XLS, CSV, and more. You can include the library in your project using either a script tag or by installing it via npm.
Using a Script Tag
Add the following script tag in your HTML file:
<script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
Using npm
If you are using a build system like Webpack or Browserify, you can install SheetJS via npm:
npm install xlsx
Then, import it in your JavaScript file:
import XLSX from 'xlsx';
Step 2: Reading the XLSX File
Let’s create a simple input element that will allow users to upload an XLSX file:
<input type="file" id="input" />
Now, we will add an event listener to the input element that will trigger the file reading process:
document.getElementById('input').addEventListener('change', handleFileUpload, false);
Finally, let’s write the handleFileUpload function that will read the XLSX file using SheetJS:
function handleFileUpload(event) { const file = event.target.files[0]; const reader = new FileReader(); reader.onload = (e) => { const data = e.target.result; const workbook = XLSX.read(data, { type: 'binary' }); // Iterate through each sheet in the workbook workbook.SheetNames.forEach(sheetName => { console.log(`Sheet: ${sheetName}`); // Get the data as a 2D array const sheetData = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], { header: 1 }); console.log(sheetData); }); }; reader.readAsBinaryString(file); }
This function reads the uploaded XLSX file as a binary string, and then creates a workbook object using XLSX.read(). It then iterates through each sheet in the workbook, and logs the data as a 2D array using XLSX.utils.sheet_to_json().
Conclusion
In this blog post, we have seen how to read XLSX files in JavaScript using the SheetJS library. This powerful library allows us to easily work with spreadsheet data in web applications, making data import and export tasks a breeze. Give it a try, and explore its extensive documentation for more advanced features!