Home >Web Front-end >JS Tutorial >How to Parse Excel (XLS) Files into JSON Format Using JavaScript/HTML5?

How to Parse Excel (XLS) Files into JSON Format Using JavaScript/HTML5?

Barbara Streisand
Barbara StreisandOriginal
2024-10-28 21:07:02711browse

How to Parse Excel (XLS) Files into JSON Format Using JavaScript/HTML5?

Parsing Excel (XLS) Files in JavaScript/HTML5

Problem:

When reading an Excel (XLS) file using FileReader, the output often contains undesirable text and characters. The goal is to parse the file row-wise, extracting data from each column and converting it to JSON format.

Solution:

To parse an XLS file row by row and convert it to JSON, follow these steps:

  1. Import necessary JavaScript libraries:
<code class="html"><script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script></code>
  1. Create a function for Excel-to-JSON conversion:
<code class="javascript">var ExcelToJSON = function() {

  this.parseExcel = function(file) {
    var reader = new FileReader();

    reader.onload = function(e) {
      var data = e.target.result;
      var workbook = XLSX.read(data, {
        type: 'binary'
      });

      workbook.SheetNames.forEach(function(sheetName) {
        // Convert sheet to row object array
        var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);

        // Convert to JSON
        var json_object = JSON.stringify(XL_row_object);

        // Output JSON object
        console.log(json_object);
      })

    };

    reader.onerror = function(ex) {
      console.log(ex);
    };

    reader.readAsBinaryString(file);
  };
};</code>

The above is the detailed content of How to Parse Excel (XLS) Files into JSON Format Using JavaScript/HTML5?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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