Microsoft Excel has been widely used for creating and managing spreadsheet files. As technology advances, Excel
has also gone through several iterations and improvements. One such change is the file format – from the older
XLS format to the newer, more versatile XLSX format. In this tutorial, we will
learn how to convert XLS files to XLSX using jQuery.
Prerequisites
Before we proceed, ensure that you have the following tools and libraries installed:
- jQuery
- SheetJS
- FileSaver.js
Steps to Convert XLS to XLSX
Follow these steps to convert XLS files to XLSX using jQuery:
1. Include the required libraries
First, include the jQuery, SheetJS, and FileSaver.js libraries in your HTML file:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
2. Create an input element for selecting the XLS file
Add an input element to allow users to select the XLS file they want to convert:
<input type="file" id="xls-file" accept=".xls"/>
3. Write the jQuery code to handle the file conversion
Now, let’s write the jQuery code to handle the file conversion:
$(document).ready(function () { $("#xls-file").change(function (e) { const file = e.target.files[0]; const reader = new FileReader(); reader.onload = function (e) { const data = e.target.result; const workbook = XLSX.read(data, { type: "binary" }); // Specify the desired output format and file extension const outputType = { bookType: "xlsx", bookSST: false, type: "binary" }; const outputData = XLSX.write(workbook, outputType); // Convert the output data to a Blob and save as a new XLSX file const buffer = new ArrayBuffer(outputData.length); const view = new Uint8Array(buffer); for (let i = 0; i < outputData.length; i++) { view[i] = outputData.charCodeAt(i) & 0xFF; } const blob = new Blob([buffer], { type: "application/octet-stream" }); saveAs(blob, "converted.xlsx"); }; reader.readAsBinaryString(file); }); });
4. Test the conversion
With the code provided above, you can now select an XLS file using the input element, and the script will
automatically convert it to XLSX format, saving the new file as “converted.xlsx”.
Conclusion
In this tutorial, we learned how to convert XLS files to XLSX using jQuery and the SheetJS library. While there
are many other ways to perform this conversion, this method provides a simple and efficient solution that can be
easily integrated into web applications.