Converting Excel sheets to JSON using Vue.js

Struggling with reading excel files in vue.js as the memory usage spikes to 5GB after processing a small file. Need help converting the file to JSON format. Tried various options mentioned in the documentation but encountered different errors. Also checked a similar query here without success.

  • base64: "TypeError: input.replace is not a function"
  • binary: "TypeError: x.charCodeAt is not a function"
  • string: "TypeError: data.match is not a function"
  • array: causing memory spike up to 5GB

Attempted to use FileReader as per documentation, however, unable to get it working properly as functions return empty results.

Both methods yielded similar outcomes:

<v-file-input
    v-on:change="displayFile($event)"
    v-model="file">
    </v-file-input>
    <input type="file" name="xlfile" id="xlf" v-on:change="displayFile($event)" />

displayFile: function (event) {
  console.log(this.file)
  this.file.text().then(text => {
    const fileType = this.file.type
    console.log(fileType)
  })
  const reader = new FileReader()
  reader.onload = (data) => {
    const workbook = XLSX.read(data, {
      type: 'buffer'
    })
    workbook.SheetNames.forEach(function (sheetName) {
      const XLRowObject = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName])
      const jsonObject = JSON.stringify(XLRowObject)
    })
  }
  reader.onerror = function (ex) {
    console.log(ex)
  }
  reader.readAsText(this.file)
}

Answer №1

To efficiently handle this, I had to adjust my approach to reading the file content. Upon using readAsBinaryString function, the process worked seamlessly, especially when utilizing the binary type. This particular method is specifically designed to extract data from only the initial sheet.

fileToJson (e) {
  const file = e.target.files[0]
  /* Initial setup for FileReader */
  const reader = new FileReader()
  reader.onload = (e) => {
    /* Parsing the retrieved data */
    const bstr = e.target.result
    const wb = XLSX.read(bstr, { type: 'binary' })
    /* Accessing the first worksheet */
    const wsname = wb.SheetNames[0]
    const ws = wb.Sheets[wsname]
    /* Converting data into array of arrays */
    const data = XLSX.utils.sheet_to_json(ws, { header: 1 })
    /* Updating state with the extracted data */
    this.data = data
    const header = data.shift()
  }
  reader.readAsBinaryString(file)
}

Answer №2

In a recent Vue CLI App project, I successfully implemented the following code:

// Ensure to import the full.min.js file only in the import statement.
import XLSX from '../../../node_modules/xlsx/dist/xlsx.full.min.js'

var reader = new FileReader()
reader.onload = function (e) {
   var data = e.target.result
   var workbook = XLSX.read(data, { type: 'binary' })
   let sheetName = workbook.SheetNames[0]
   let worksheet = workbook.Sheets[sheetName]
   let rowObject = XLSX.utils.sheet_to_row_object_array(worksheet)
   const finalJsonData = JSON.stringify(rowObject, undefined, 4)
   console.log(finalJsonData)
}
reader.readAsBinaryString(this.excelFile)

The resulting JSON output looked like this:

[
    {
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cebaabbdbafb8ebaabbdbae0ada1a3">[email protected]</a>",
        "password": "password",
        "full_name": "Some Name 5",
        "mobile": 9897675463
    },
    {
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="32465741460472465741461c515d5f">[email protected]</a>",
        "password": "password",
        "full_name": "Some Name 6",
        "mobile": 9897675463
    },
    ...
    ...
]

Furthermore, the Excel file used can be viewed here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Chrome extension functions properly when the page is refreshed or loaded, but it does not work with internal navigation

When landing on a YouTube page starting with w*, I have a script that triggers an alert with the URL. However, this only works when entering the page directly or upon refreshing. I am trying to make the alert trigger when navigating internally to that page ...

What is the process for 'injecting' data into a Vue component?

Trying to understand components better and struggling to adapt the official vuejs.org guide examples from new Vue({...}) to the module structure in a newly created Vue app using the CLI. If I have something like this: const products = { 'bat': ...

Issue with repeated items in Flatlist

Whenever I display my flatlist, it appears to be duplicating the items within it (the feedCache has only one index but the data for this index is rendered twice). Below is the code snippet for the flatlist: const FeedBody = React.memo(() => { return ...

Tips for navigating upwards to a specific element and successfully clicking on it in Selenium

I am facing a situation where the system needs to scroll upwards to reach the web element located in the left panel of the page and then click on it to proceed with other operations. I have attempted various methods but none seem to be effective. Can anyon ...

"Can you provide guidance on binding data in vue.js when there is a dash (-) in the key of the JSON

My JSON data is structured as follows: { "color-1": "#8888", "color-2": "#000" } I am attempting to bind this variable with a style tag for a Vue component. However, my current approach seems to not be functioning as expected. <div v-bind:sty ...

Connecting NGINX to a Node.js cluster with proxy_pass

After setting up both a NGINX server and a node.js process, the node.js code structure is as follows: function initiateCluster() { var numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers. for (var i = 0; i ...

Embed the website onto a webpage using ajax or an iframe without any need for navigation

I have a unique challenge ahead. Imagine there are two websites, one is a web page and the other is hosted within the same domain. My goal is to load the entire second website into a div or iframe of the first web page, similar to how a free proxy browser ...

Customize Vue or Nuxt by including a highly detailed tag in the <head> section

Trying to generate static page templates using Vue/Nuxt but struggling to find a way to insert a very specific tag into the head section of each generated page. It's not a meta, script, style, or link tag, and it appears that the options in nuxt.confi ...

Is it possible to showcase the data from three or more PHP files on a single webpage?

I currently have three PHP files: pie.php, bar.php, and line.php. When each file is run individually, it displays a webpage with a pie chart, bar chart, or line graph respectively. However, running all three files opens up separate webpages for each graph. ...

Attempting to input data into elements that have been generated automatically

Trying to set values to elements with automatically generated id's: This code is functional: <input type="tekst" id="<?php echo $item->getId();?>"> <script> document.getElementById("<?php echo $item->getId();?>").v ...

How to prevent npm from being accessed through the command prompt

I recently began working on a ReactJs project. However, I am facing an issue where after starting npm in Command Prompt, I am unable to enter any text. Should I close the cmd window or is there a way to stop npm? You can now access your project at the fol ...

Efficiently showcase connected pages in real-time

I've come across an issue with my express app. Whenever a navigation link (such as Home, Home1, or Home2) is clicked, an error occurs. However, if I manually type in http://localhost:8001/home1, it displays home1.html without any issues. What I' ...

Discovering methods to store browser credentials securely in jQuery

I need to prevent the login button from being enabled when either the username or password fields are empty. Check out the code snippet below: $(document).ready(function(){ $('input').on('keyup blur mouseenter', function(e) { ...

the deactivation of my rollover class is being caused by my float class

With the assistance of a generous contributor on stackoverflow, I was able to overlay different colored CSS boxes onto various images. These boxes could be removed upon mouseover, revealing the images beneath. You can view the code I used on fiddle here. ...

Center the image within the div by setting its position to absolute

<div class='img-box'> <img /> //position absolute <img /> //position absolute <img /> //position absolute <img /> //position absolute I am struggling to center the images within this div because of their absolute p ...

CSS Flexibility in Action

Presently, my tab bar has a fixed look as shown here: https://codepen.io/cdemez/pen/WNrQpWp Including properties like width: 400px; etc... Upon inspecting the code, you'll notice that all the dimensions are static :-( Consequently, I am encountering ...

The state may be modified, but the component remains unchanged

I've been tasked with implementing a feature on a specific website. The website has a function for asynchronously retrieving data (tickets), and I need to add a sorting option. The sorting process occurs on the server side, and when a user clicks a s ...

Send back alternate HTML content if the request is not made via AJAX

Last time I asked this question, I received several negative responses. This time, I will try to be more clear. Here is the structure of a website: Mainpage (Containing all resources and scripts) All Other pages (HTML only consists of elements of that ...

Automatically Dismissing a Bootstrap Alert After a Set Number of Seconds

Having some trouble closing a Bootstrap alert automatically on my new site built using the Bootstrap Framework. The issue arises when trying to close the alert after a certain amount of time. On the main page of the site, there is a modal login form. When ...

Creating dynamic cubes in Magento with interact.js within a .phtml template

I utilized the interact.js library to create this code snippet, which functions perfectly on Chrome, Firefox, and w3schools "Try it Yourself" platform (unfortunately not compatible with Edge and IE for unknown reasons). However, when I include this code wi ...