Parsing Excel (XLS) Files in Javascript/HTML5
Converting Excel files to JSON format is a common need for web applications. However, reading XLS files using FileReader can pose some challenges, such as incorrect formatting and special characters.
To address this issue, the key is to use row-by-row iteration to extract data from each column and convert it to JSON. Here's a detailed approach:
Function for XLSX Conversion:
The following function can be used to convert Excel sheets in XLSX format to JSON:
<code class="javascript">const ExcelToJSON = () => { this.parseExcel = (file) => { const reader = new FileReader(); reader.onload = (e) => { const data = e.target.result; const workbook = XLSX.read(data, { type: 'binary', }); workbook.SheetNames.forEach((sheetName) => { const XL_row_object = XLSX.utils.sheet_to_row_object_array( workbook.Sheets[sheetName], ); const json_object = JSON.stringify(XL_row_object); console.log(json_object); }); }; reader.onerror = (ex) => { console.log(ex); }; reader.readAsBinaryString(file); }; };</code>
This function uses the XLSX library to read the Excel file as a binary string and then iterate through each sheet. For each sheet, it converts the data to a row-object array using sheet_to_row_object_array. Finally, the array is converted to JSON format.
XLS Format Conversion:
For XLS files, the following post provides a JavaScript code snippet that can be used to convert them to JSON:
[XLS Format Excel to JSON Javascript Code](link to the post)
The above is the detailed content of How to Convert Excel (XLS) Files to JSON in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!