Home > Web Front-end > JS Tutorial > body text

How to Convert Excel (XLS) Files to JSON in JavaScript?

Barbara Streisand
Release: 2024-10-29 15:42:02
Original
541 people have browsed it

How to Convert Excel (XLS) Files to JSON in JavaScript?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template