In a VueJS project, access an xlsx file stored in the public directory by reading its contents

My current challenge involves trying to extract a quiz template from an xlsx file in order to create the quiz within it.

Unfortunately, storing the xlsx file as json in a database is not a feasible solution for me at this time.

I experimented with using the xlsx library to directly read the file located in the public directory, but encountered difficulties as the path to the file could not be found. Upon investigating further, I discovered that most browsers do not allow reading files in this manner due to security concerns.

Is there a way to access xlsx files stored directly in the public directory?

This is what my attempt looked like :

handleFile() {
    const workbook = XLSX.readFile('/xlsx/quiztemplate.xlsx')
    const firstSheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[firstSheetName]
    const excelData = XLSX.utils.sheet_to_json(worksheet)
    console.log(excelData)
  }

However, I encountered the following error :

Uncaught Error: Cannot access file /quiz/quiztemplate.xlsx

Despite double-checking the file path multiple times, I am confident that it is not the issue. While the documentation mentions browser restrictions on this functionality, I am uncertain if that is the root cause because the function still attempts to read the file.

Answer №1

If you are working in a server-side (Node.js) environment, XLSX.readFile() is the function designed for you.

To make use of it, simply run:

npm install xlsx

Unfortunately, when it comes to using readFile() in a browser environment, things get a bit more complex. You'll need to fetch the file as a blob and then process it.

<template>
  <div>
    <button @click="handleFile">Load Quiz</button>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';

export default {
  methods: {
    async handleFile() {
      try {
        const response = await fetch('/xlsx/quiztemplate.xlsx');
        const data = await response.arrayBuffer();
        const workbook = XLSX.read(data, { type: 'array' });
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        const excelData = XLSX.utils.sheet_to_json(worksheet);
        console.log(excelData);
      } catch (error) {
        console.error("Error reading the Excel file:", error);
      }
    }
  }
}
</script>

Here's why this works:

The fetch API allows you to retrieve files from your public directory in a Vue.js project. The fetched data needs to be converted to an ArrayBuffer because Excel files are binary.

By using XLSX.read() from the xlsx library with the type set to 'array', you can effectively parse the binary data and manipulate it further.

After that, extracting the necessary sheet and converting it to JSON should go smoothly as intended.

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

Implementing user authentication in node.js with passport

Having trouble with a basic login system using passport. I keep getting an error when logging in with the correct credentials: Error: Express 500 TypeError - Cannot read property 'passport' of undefined Oddly enough, everything works fine when ...

Paste a data point from an Excel spreadsheet into a JavaScript script

I'm encountering a major challenge. Currently, I am creating a login process for a client and here is the approach I have taken: function Jump(pal){ if (pal=='10528'){window.open('http://www.google.es','_parent')} Subs ...

Tips on adjusting the pixel dimensions of an image using a file object

Within a form on our website, users have the ability to upload an image file. To ensure quality control, I've set up validation to confirm that the uploaded file is either an image or gif format. In addition to this, I'm looking for a solution th ...

Encountered a SyntaxError while deploying Nuxt.js SSR on Passenger: The import statement cannot be used outside a module

I am currently in the process of deploying my Nuxt app on a hosting service that uses Passenger to run Node.js applications. After building the app with the command ">npm run build" and deploying the content from the .nuxt folder onto the server, specif ...

Dynamic updating of scores using Ajax from user input

My goal is to design a form that includes three "Likert Scale" input fields. Each of these three inputs will have a total of 10 points that can be distributed among them. The submit button should become enabled when the score reaches 0, allowing users to s ...

What are the steps to retrieving information in Vue 3?

I'm encountering an issue with fetching data using Vue 3. I've set up an action to call an endpoint (), but I'm not receiving any response data. The defined endpoint is as follows: import { createStore } from 'vuex' export d ...

Passing a component as a prop in Vue3 allows for more

I'm currently working on a tab component that requires passing a component as a prop. How can I properly display the component passed in the props? Here is my Tab.vue code: <template> <div class="bg-white flex items-center rounded-tr ...

Encountering difficulties when attempting to test Vue CSS styling

Encountering difficulties in my unit tests while attempting to test a method that alters the CSS style "display" to "none". The test fails with this message: Expected: "display: none" Received: undefined Within my component, there is a method: closeCook ...

Why am I unable to retrieve data using jQuery and PHP?

I'm working with a PHP form that involves checkboxes: <form action="" method="post" id="CheckBoxForm"> foreach ( $results as $result ) : <input type="checkbox" class="chk" id="check_list[]" value="'.($result->meta_value).&a ...

What is the best way to generate a hyperlink that will open a raphael graph in my own browser?

If I have a web page that includes a raphael.js drawing in <div id='my-canvas'></div> <body> <div id='part_one'>...</div> <div id='my-canvas'></div> <div id='part_thre ...

Manipulating arrays in JavaScript through HTML processing

I'm encountering an issue while trying to send an array to a JavaScript function. Here's what I have so far: Within the controller: @data = [{date: '2014-08-17'}, {date: '2014-08-20'}].to_json In the view: <%= content_t ...

Change a camelCase string to ALL_CAPS while adding underscores in JavaScript

Currently, I'm dealing with a situation where I have a list of variables stored in a file that I need to convert into all capital letters and separate them with underscores using JavaScript. The variable pattern looks something like this: AwsKey Aw ...

Incorporating an express server into the vue-webpack-boilerplate for enhanced functionality

Recently, I got my hands on the vue-webpack-boilerplate from GitHub, and so far, it seems pretty impressive! This is my first time working with webpack and ESlint, so I'm eager to learn more. However, I have a question about integrating an express ba ...

Looping through a series of URLs in AngularJS and performing an $

Currently, I am facing an issue while using angular.js with a C# web service. My requirement is to increment ng-repeat item by item in order to display updated data to the user. To achieve this, I attempted to utilize $http.get within a loop to refresh t ...

Encountering a 404 error while accessing my meticulously crafted express server

After ensuring that the server is correctly set up and without any errors related to imports or missing libraries, I utilized cors for development purposes. A 404 error persisted even after attempting to comment out the bodyparser. https://i.stack.imgur.c ...

Detection of collisions using bounding sphere method

In Three.js, each mesh (THREE.Object3D) comes with useful properties like boundingSphere and boundingBox, along with methods such as intersectsSphere and isIntersectionBox. I initially thought I could use these for simple collision detection. However, I n ...

Troubleshooting app.use in Next.js and express.js: Understanding the issue

Currently, I am working on a project using next.js along with a custom server (express.js). In my API endpoints, I want to utilize some middlewares (such as const attachUser), but strangely I am facing issues when trying to use app.use. The code seems to ...

Deleting the Last Node in a Linked List

My current project involves creating a function that removes the last node of a given list passed in as an argument. The function itself is relatively simple and is shown below. function popBack(list) { var current = list.head, previous; ...

Is it possible to send an ajax request within another ajax request?

I'm facing an issue with a php file that is sending an ajax request to another file located on a different domain name. The receiving parser then processes the information and sends it via ajax to yet another php file where the final action is carried ...

Is the $http call for OPTIONS instead of POST?

Hey there, I'm encountering a strange issue while trying to call my backend using the POST method. Remote Address:192.168.58.183:80 Request URL:http://192.168.58.183/ESService/ESService.svc/CreateNewAccount Request Method:OPTIONS Status Code:405 Meth ...