Read Excel File In VueJS

Introduction:

Excel is frequently used for data organization and financial analysis. It is utilized by businesses of all sizes and in all business operations.

This post demonstrates how to read an excel file in VueJS. In order to read the excel file, we start over completely by installing VueJS.

 

Get Started:

Step 1:

Install Vue CLI in your system. You can use the following commands to install the new package. Unless npm was installed on your system using Node.js version management, you need administrator rights to run them (e.g. n or nvm).

npm install -g @vue/cli

After installation, your command line will have access to the Vue binary. Run Vue to see if it was correctly installed; you should then get a help message outlining all the commands that are available.

With this command, you may verify that you are using the correct version:

vue --version

 

Step 2:

Create a new project by running this command.

vue create read-excel

 

Step 3:

Install XLSX package using this command.

npm i xlsx

 

Step 4:

Import XLSX into your HelloWorld.vue file.

import * as XLSX from "xlsx";

 

Step 5:

Add this code in your <template> section.

<template>
  <div class="hello">
    <div>
      <input
        type="file"
        v-on:change="addfile($event)"
        placeholder="Upload file"
        accept=".csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
      />
    </div>
  </div>
</template>

 

Step 6:

Declare the variables in the data function.

data: function(){
    return {
      file: File,
      arrayBuffer: null,
      filelist: null
    };
  },

 

Step 7:

Add the addfile() function in the methods section.

addfile(event) {
  this.file = event.target.files[0];
  let fileReader = new FileReader();
  fileReader.readAsArrayBuffer(this.file);
  fileReader.onload = (e) => {
    this.arrayBuffer = fileReader.result;
    var data = new Uint8Array(this.arrayBuffer);
    var arr = new Array();
    for (var i = 0; i != data.length; ++i)
      arr[i] = String.fromCharCode(data[i]);
    var bstr = arr.join("");
    var workbook = XLSX.read(bstr, { type: "binary" });
    var first_sheet_name = workbook.SheetNames[0];
    var worksheet = workbook.Sheets[first_sheet_name];
    console.log(XLSX.utils.sheet_to_json(worksheet, { raw: true }));
    var arraylist = XLSX.utils.sheet_to_json(worksheet, { raw: true });
    this.filelist = [];
    console.log(this.filelist);
  };
}

 

Finally, run the project by

npm run serve

You can see the output on the http://localhost:8080. Then open the console and see the output in it.

 

Output:

 

 

 

 

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories