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

Using AngularJS $http.jsonp() method to interface with Google Maps Distance Matrix API

I am currently working on integrating the Google Maps Distance Matrix API into my project to calculate distances between two points using specific coordinates. My implementation involves AngularJS and the $http.jsonp() method to make requests to the API: ...

In the event of a 404 error, simply direct the user to the pageNotFound before ultimately guiding them back

I'm developing a website with Node JS and I want to implement a feature where if the user attempts to navigate to a non-existent page, they are redirected to a "Page Not Found" message before being automatically taken back to the home page after a few ...

Utilize a vanilla JavaScript object as the primary model in Ember

Can a plain JS object, such as a literal object, be used as a model in EmberJS? I've noticed that all the examples in the documentation utilize Ember.Object or a datastore. I understand that I may not have access to features like observables with pl ...

Pressing the reset button will restore the table to its original

As a new React developer with experience mainly in hooks, I have been struggling to find a good example involving hooks. Currently, I am working on implementing an antd table with search functionality. My question is, when a user types something into the ...

Increase the options available in the dropdown menu by adding more selected items, without removing any already selected

I came across this code on the internet http://jsfiddle.net/bvotcode/owhq5jat/ When I select a new item, the old item is replaced by the new item. How can I add more items without replacing them when I click "dropdown list"? Thank you <select id=&qu ...

How can I modify the mesh structure in Three.js?

Having two meshes, mesh1 and mesh2, each with the same number of vertices and extrusion. mesh1 = 5000 vertices. mesh2 = 5000 vertices. I transfer the vertices from mesh2 to mesh1. Then I execute: mesh2.geometry.verticesNeedUpdate = true; mesh2.geometry. ...

Animating a 3D object along a path in Three.js

I am trying to shoot a projectile from one mesh to another. I connected them with a line, but now I'm struggling to move the projectile along this path. The translateOnAxis function didn't seem to do the job. Do you have any suggestions for how ...

Error: Unable to locate module: Unable to locate '@material-ui/core/Container'

Encountering an error in the browser: Error message: Module not found: Can't resolve '@material-ui/core/Container' The search for the component is directed towards my components directory instead of node_modules. Unfortunately, changing ...

What is an alternative method to retrieve POST fields in Express without relying on the bodyParser middleware?

Recent updates to Express have suggested to stop using the bodyParser middleware, as indicated by a debug message. Upon further research, it appears that bodyParser is simply a wrapper to the json and urlencoded middlewares. In its place, the latest versio ...

Notify when the SVG object is clicked based on its identifier

I'm interested in adding more complexity to this project, but before I can proceed, I need to be able to detect when a specific object element containing an SVG image with an ID is clicked. Each object is nested within a div. <div class="grid 18"&g ...

Using ASP.NET Server Controls to Toggle Textbox Visibility Based on Dropdown Selection

What is the optimal method for displaying or hiding a textbox or an entire div section based on a user's selection from a dropdown menu? I am uncertain if this can be achieved with server controls, so would it require using standard client-side HTML c ...

accessing the angular fullstack default application by authenticating via google oauth2

Currently, I have my angular fullstack application running on localhost:9000. I am trying to implement a feature that allows users to log in by clicking the "Connect with Google+" button on the login page. However, I keep encountering an error 400 with th ...

Filtering out specific properties in an array using Angular

I am facing an issue with my Angular filter when inputting text for a specific list. initialViewModel.users = [ {user: 'Nithin',phone: 'Azus', price: 13000}, {user: 'Saritha',phone: 'MotoG1',price: 12000}, {user: ...

Guide on showing a dropdown menu depending on the data in the current array index within a table

I am working with an object array that I want to display in a table. My goal is to have a dropdown select if the 'validvalues' field is not empty. How can I achieve this so that each row in the table has different options from the array? When &ap ...

Need to update React textarea with value that is currently set as readonly

In my React application, I have a textarea that is populated with a specific value. My goal is to allow this textarea to be updated and then submit the form in order to update the corresponding row in the database. <textarea id="description" className= ...

Is your Vuex state data not persisting properly?

I am currently developing an admin panel using Vue.js and utilizing Vuex for state management. store/module/home/home.js: import instance from "../../../services/Http"; const state = { usersCount: 0, customersCount: 0, chefsCount: 0, d ...

How to dynamically display content based on option selection in AngularJS using ng-show

I am trying to create a functionality where my input field is bound to my select option. When the select option is set to Yes, I want the input field to be visible, and when it's set to No, I want the input field to be hidden. (function(){ var app ...

Using jQuery, how can you make fixed elements fade as the page scrolls?

How can I make a fixed element, such as a corner ad or notice, fade when the page is scrolled down to a certain point? What would be the most effective method for determining this point: using pixels, percentage, or another way? And how can I implement th ...

Vue is lagging behind in implementing Virtual Dom technology

I have come across this code snippet. <template> <div ref="nodesData"> <div v-for="(item, index) in nodes" :key="index" :id="item.id"> {{ item.id }} </div> <div> ...

jQuery AJAX Triggered Only Once in Callback Function

I am facing an issue with the jQuery get function within my updateMyApps. The function works fine when called directly after it is declared. It successfully loops through the data and appends elements to the DOM. However, when I submit the form #addapplic ...